Sed command to print matching lines and 2 lines above..
Hello everyone,
I'm looking to print matching lines including the 3 lines above the matched line. I have come up with the following command but it's only printing 1 line above. In the example below the output is missing the Host Name and the following blank line. Anyone known what I'm missing here? sed -n /192.168.12/{x;p;x;p};h <input.txt >output.txt input.txt Host Name: SERVER1 NetBIOS over TCP/IP: Enabled IP Address: 192.168.12.111 ----------------------------- output.txt NetBIOS over TCP/IP: Enabled IP Address: 192.168.12.111 |
If you're not trying to replace any of the text, then the grep command has an option to do this:
Code:
grep -B 3 "192.168.12.11" <file.txt> > outfile.txt |
Thanks crc123, but is there anyway SED can do this?
|
Quote:
This said, I will confess that I often do such things---if only to see if it can be done. The problem with SED is that it operates one line at a time. To do what you want, you have to append lines to the hold register and then pull out the combination to test it. If the test failed, you would then have to delete one of the lines and add a new one. I visualize some messy-looking code.... Really good SED tutorial here: http://www.grymoire.com/Unix/Sed.html |
|
Maybe this could work:
Code:
sed -n '/Host Name/,/192.168.12.111/p' input.txt > output.txt |
I think OP wanted the 3 previous lines without knowing the content...ie the only thing known was the desired pattern in the last line.
|
Quote:
Code:
awk ' Code:
# more file |
If the file is not too large:
Code:
perl -0ne'print /((?:.*\n){3}.*search pattern.*\n)/g' filename |
Quote:
That's correct, I don't know the value of the previous lines. |
I finally figured out the original syntax:
Code:
sed -n /192.168.12/{x;p;x;p};h <input.txt >output.txt What you need is "H" (append), instead of "h" (copy) This is crude, but works: Code:
sed -n '/keyword/{H;g;p};H' filename|tail -n3 > newfilename |
The following is adapted from a sed emulation of the tail command at
http://www.gnu.org/software/sed/manual/sed.html#tail It creates a moving window of four lines. The '$' end of line marker is essential as the pattern space will usually contain four file lines and '192.168.12.111' could be in any of them, but we only want to print when its in the last one, i.e. at the end of the pattern space. Code:
sed -n '1h;2,4 {; H; g; };/192.168.12.111$/p;1,3d;N;D' input.txt Code:
tac input.txt | sed -n '/192.168.12/,+3p' | tac These solutions give the matched line and the three lines above. If only two lines above are required change 4 to 3, and 3 to 2 in the code. (Both versions of the problem appear in the thread) |
Thank You! I get it now...you guys are amazing!
|
All times are GMT -5. The time now is 10:48 PM. |