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
SED Search Pattern and Replace with the Pattern racbern Shell Programming and Scripting 4 03-15-2008 01:59 AM
Search Mulitiple String pattern in a file krishnan_6015@y Shell Programming and Scripting 2 11-23-2007 12:03 AM
Reading lines in a file matching a pattern torenji Shell Programming and Scripting 4 10-25-2007 01:15 AM
File search for pattern - script rahulrathod Shell Programming and Scripting 3 02-16-2007 12:03 AM
Search a file for pattern? davjoyce UNIX for Dummies Questions & Answers 2 03-07-2006 02:07 PM

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 12-22-2005
Registered User
 

Join Date: Aug 2003
Posts: 252
Search file for pattern and grab some lines before pattern

I want to search a file for a string and then if the string is found I need the line that the string is on - but also the previous two lines from the file (that the pattern will not be found in)

This is on solaris

Can you help?
Reply With Quote
Forum Sponsor
  #2 (permalink)  
Old 12-22-2005
Registered User
 

Join Date: Jul 2005
Location: Chennai
Posts: 39
There is some option for grep itself for this same purpose like grep -An (for getting n lines above the searched pattern) and grep -Bn (for getting n lines below the searched pattern) ... not sure if this is there for solaris ... i think no ...

meanwhile u can try out this solution as well ...

grep -n pattern filename | cut -d":" -f1 | xargs -i expr {} - 2 | xargs -i sed -n '{},/pattern/ p' filename
Reply With Quote
  #3 (permalink)  
Old 12-22-2005
Registered User
 

Join Date: Jul 2005
Posts: 137
Awk:
Code:
NR>3 { delete a[NR-3] }
/find this/ { print a[NR-2]; print a[NR-1]; print }
{ a[NR] = $0 }
Reply With Quote
Google UNIX.COM
Reply

Thread Tools
Display Modes




All times are GMT -7. The time now is 01:54 AM.


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

Content Relevant URLs by vBSEO 3.2.0