Unix/Linux Go Back    

Shell Programming and Scripting Unix shell scripting - KSH, CSH, SH, BASH, PERL, PHP, SED, AWK and shell scripts and shell scripting languages here.

awk or sed for finding closest pattern to a line number

Shell Programming and Scripting

Closed Linux or Unix Question    
Thread Tools Search this Thread Display Modes
Old Unix and Linux 10-10-2008
alirezan alirezan is offline
Registered User
Join Date: Aug 2008
Last Activity: 13 March 2009, 9:09 PM EDT
Posts: 22
Thanks: 0
Thanked 0 Times in 0 Posts
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:



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?
Sponsored Links
Old Unix and Linux 10-11-2008
Franklin52's Unix or Linux Image
Franklin52 Franklin52 is offline Forum Staff  
Join Date: Feb 2007
Last Activity: 29 May 2016, 11:39 AM EDT
Location: The Netherlands
Posts: 7,746
Thanks: 138
Thanked 559 Times in 521 Posts
Should be something like:

awk '
/qqq/{for(i=1;i<=c;i++){print a[i]}exit}
' file

Sponsored Links
Closed Linux or Unix Question

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

Linux More UNIX and Linux Forum Topics You Might Find Helpful
Thread Thread Starter Forum Replies Last Post
[Solved] Finding the next line when a pattern matches mr_manii Shell Programming and Scripting 3 10-04-2011 05:52 AM
Closest Number from a Range of Numbers SkySmart Shell Programming and Scripting 6 08-16-2011 01:52 PM
finding the line number of a particular line in a file mvignesh Shell Programming and Scripting 3 07-06-2011 11:44 AM
delete rows between closest pattern or range sudheer1984 Shell Programming and Scripting 10 01-21-2010 08:26 AM
sed match closest/nearest pattern sudheer1984 UNIX for Advanced & Expert Users 1 07-02-2009 03:59 AM

All times are GMT -4. The time now is 01:16 PM.