2

I would like to search a file for multiple strings and for one particular string, show the 5 lines following it as well.

cat file | grep -e 'string1' -e 'string2'

works of course, but I would like to get something like

cat file | grep -e 'string1' -e -A 5 'string2'

How can I make it so that (I'm assuming using the -A 5 option) it shows only the lines containing string1 and only the lines containing string2 and the 5 lines after string2, but not the 5 lines after string1?

EDIT: just got it working with awk:

cat file | awk '/string1/{c=1}/string2/{c=5}{while(c-->0){print;getline}}'

migrated from serverfault.com Sep 17 '15 at 9:52

This question came from our site for system and network administrators.

0

You can't do that using one go of grep. You need to use two grep instances :

grep 'string1' file; grep -A 5 'string2' file

If you want to run the second upon success of the first one :

grep 'string1' file && grep -A 5 'string2' file
0

about awk code

awk '/string1/{if ( c<=0 ) c=1 ;}/string2/{c=5}{ if (c-->0) print;}' file
  • do not cat ... | awk ,awk can read file.
  • I rearrange test (if string1 is one line after string2, it interrupt printing in OP's solution)
  • To much ifs… awk '/string2/{c=NR+5}/string2/,NR==c{print;next}/string1/' – Costas Sep 17 '15 at 11:26
  • Your shorted variant is awk '/string2/{c=4;do{print;getline}while(c--)}/string1/' – Costas Sep 17 '15 at 11:32
0

Sed solution:

sed -n '/string2/,+4{p;b;};/string1/p' file

my sed also accept ~ instead of +

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy