Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining -v flag and -A flag in grep

Tags:

grep

unix

sed

I need to search a file for a string, remove any line that contains the string, and also remove the two lines following any line that contains the string. I was hoping I could accomplish this using something like this...

$ grep -v -A 2 two temp.txt
one
five
$

...but unfortunately this did not work. Is there a simple I can do this with grep or another shell command?

like image 829
Daniel Standage Avatar asked Apr 17 '13 01:04

Daniel Standage


3 Answers

The following works both with GNU sed and with OS X.

$ sed '/two/{N;N;d;}' temp.txt
one
five
  • find line matching two
  • read in two more lines
  • delete them
like image 52
3 revs, 2 users 69% Avatar answered Oct 14 '22 22:10

3 revs, 2 users 69%


You can do this with awk, as per the following transcript:

pax> echo 'one
two
three
four
five' | awk '/two/ {skip=3} skip>0 {skip--;next} {print}'

one
five

It basically starts a counter of lines to throw away (3) whenever it finds the two string on a line. It then throws those lines away until the skip counter reaches zero. Any line that isn't marked for skipping is printed.

like image 44
paxdiablo Avatar answered Oct 14 '22 23:10

paxdiablo


With GNU sed:

sed '/two/,+2d' temp.txt

This uses two-address syntax (addr1,addr2) to match lines with the word two (/two/) plus the two lines after (+2). The d command deletes those lines.

like image 3
John Kugelman Avatar answered Oct 14 '22 22:10

John Kugelman