Multiple patterns with multiple contexts?
I want grep to search for two patterns, and output different lines of context for each match: e.g, when it matches "warning", output 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 -开发者_如何学JAVAne "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 doesn't work - apparently, only the final -B
/-A
arguments are effectuated for all patterns.
Does anyone have an idea how to achieve separate context for each search pattern?
What about this variant using sed
?
sed -n '/warning/{x;p;x;p;n;p};/error/{x;p;x;p;n;p;n;p};h'
Where x
means Exchange the contents of the hold and pattern spaces,
p
means Print the current pattern space
n
means Read the next line of input into the pattern space
h
means Copy pattern space to hold space
sed -n
means suppress automatic printing of pattern space (i.e. print only when p
occurs)
精彩评论