The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > Shell Programming and Scripting
Google UNIX.COM


Shell Programming and Scripting Post questions about KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and OTHER shell scripts here.

More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
Finding the line number of matching braces Rajendra_1510 Shell Programming and Scripting 3 10-07-2008 02:08 AM
Split File Based on Line Number Pattern shankster Shell Programming and Scripting 11 10-01-2008 06:49 AM
Finding Last occurance of another pattern when a pattern is found. rakeshou Shell Programming and Scripting 1 07-23-2008 12:29 PM
finding duplicate files by size and finding pattern matching and its count jerome Sukumar Shell Programming and Scripting 2 12-01-2006 01:20 AM
Finding pattern & prepending a line with text kirrushna Shell Programming and Scripting 1 07-10-2006 11:20 PM

Reply
 
Submit Tools LinkBack Thread Tools Display Modes
  #1  
Old 10-10-2008
Registered User
 

Join Date: Aug 2008
Posts: 19
awk or sed for finding closest pattern to a line number

hi guys,

I want to do pattern matching with awk or sed but I don't know how. here's what I want:

I have a line number for a pattern that I have already found using grep, and I know a pattern like "---" that happens a few lines above that certain line number. I want to print out the chunk between "---" and that line number. But here's the catch. the pattern "---" can be between 1 and 20 lines above that line number and I don't know how many lines above ... Also, another catch is that, "---" can happen multiple times in the file but I want the "CLOSEST" to the line number. Here's an example:

Here's the file:

Quote:
---
aaa
bbb
ccc
ddd

---
aaaa
bbbb
cccc
dddd
eeee
ffff
gggg
hhhh

---
jjj
dsf
qqq
www
eee
I found the pattern say qqq to be on line 20. I want to find the first --- before pattern qqq (line 20) and I want to print the entire chunk from --- till the qqq pattern printed out.

Can someone help me out here please?
Thanks
Reply With Quote
Forum Sponsor
  #2  
Old 10-11-2008
Moderator
 

Join Date: Feb 2007
Posts: 2,204
Should be something like:

Code:
awk '
/---/{c=0}
{a[++c]=$0}
/qqq/{for(i=1;i<=c;i++){print a[i]}exit}
' file
Regards
Reply With Quote
Google The UNIX and Linux Forums
Reply

Thread Tools
Display Modes




All times are GMT -7. The time now is 01:53 PM.


Powered by: vBulletin, Copyright ©2000 - 2006, Jelsoft Enterprises Limited.
The UNIX and Linux Forums Content Copyright ©1993-2008. All Rights Reserved.Ad Management by RedTyger Visit The Complex Event Processing Blog

Content Relevant URLs by vBSEO 3.2.0