Results 1 to 5 of 5
Hi,
I need to kind of grep within grep. My input file would be something like:
blah blah
hello 2545
blah blah
blah blah
blah blah
hello 9008
blah blah
...
- 11-22-2010 #1Just Joined!
- Join Date
- Sep 2010
- Posts
- 12
grep within grep
Hi,
I need to kind of grep within grep. My input file would be something like:
blah blah
hello 2545
blah blah
blah blah
blah blah
hello 9008
blah blah
blah blah
blah blah
MY PATTERN
blah blah
blah blah
blah blah
and I need to find the first occurrence of hello before MY PATTERN (hello 9008 in this case), so the output should be:
hello 9008
MY PATTERN
How can I do this?
Thanks,
- 11-22-2010 #2
I wouldn't use grep for this, since grep does line matching only... You could write a script which reads the file and checks every line for the hello pattern. If it matches, it saves the line in a variable. Then, it checks for your MY PATTERN, if it matches, it appends the MY PATTERN line to the variable you saved the previous match in. Sounds complicated, but it's actually pretty easy..
That's probably not the easiest way, but it works.
Do you know anything about perl? You can write a bash script, too, but with perl it's very easy!
- 11-22-2010 #3Linux Enthusiast
- Join Date
- Apr 2004
- Location
- UK
- Posts
- 658
Hi there,
You can pipe the output of one grep into another.
Using several -e switches lets you match several patterns, in this case the lines starting "hello" and the lines with "MY PATTERN" in them. The -B flag gives extra lines of context, in this case one line backwards.Code:chris@angua:~$ cat test.txt blah blah hello 2545 blah blah blah blah blah blah hello 9008 blah blah blah blah blah blah MY PATTERN blah blah blah blah blah blah chris@angua:~$ grep test.txt -e ^hello -e "MY PATTERN" | grep -B 1 "MY PATTERN" hello 9008 MY PATTERN
You may get strange effects if you have several instances of your pattern without hello lines in between, but whether that is an actual problem depends on what you are trying to do.
Let us know how you get onTo be good, you must first be bad. "Newbie" is a rank, not a slight.
- 11-22-2010 #4
- 11-23-2010 #5Just Joined!
- Join Date
- Sep 2010
- Posts
- 12
It worked GREAT! I didn't know about the -e switch. That's exactly what I wanted to do.
Thank you very much


Reply With Quote
