Multiple templates with multiple contexts?

I want grep to look for two patterns and output different lines of context for each match: for example, when it matches โ€œwarningโ€, it prints 1 line before and 1 line after - and when it matches โ€œerrorโ€, output 1 line before and 2 lines after; so i tried this:

$ echo -ne "1\n2\n3\n4\nwarning\n5\n6\n7\n8\nerror\n9\n10\n11\n12\n" | grep -e "warning" -A 1 -B 1 -e "error" -B 1 -A 2 4 warning 5 6 -- 8 error 9 10 

... however, unfortunately, it does not work - apparently, only the final arguments -B / -A implemented for all templates.

Does anyone have an idea how to achieve a separate context for each search template?

+4
source share
1 answer

How about this option with sed ?

 sed -n '/warning/{x;p;x;p;n;p};/error/{x;p;x;p;n;p;n;p};h' 

Where x means sharing the contents of the hold space and the template,
p means print current pattern space
n means reading the next line of input into the pattern space
h means copy pattern space to save space
sed -n means suppress automatic printing of pattern space (i.e. print only when p occurs)

+4
source

All Articles