具有多个上下文的多种模式? [英] Multiple patterns with multiple contexts?
问题描述
$ echo -ne1\\\
2\\\
3\\\
4\\\
warning\\\
5 \\\
6\\\
7\\\
8\\\
erner\\\
9\\\
10\\\
11\\\
12\\\
| grep -e警告-A 1 -B 1 -e错误-B 1 -A 2
4
警告
5
6
-
8
错误
9
10
然而,不幸的是它不起作用 - 显然,只有最终的 -B
/ -A
所有模式。
有没有人有一个想法如何为每个搜索模式实现单独的上下文?
这个变体使用 sed
?
sed -n'/ warning / {x; p; x; p; n; p}; / error / {x; p; x; p; n; p; n; p}; h'
其中 x
意味着交换保留和模式空间的内容,
p
表示打印当前图案空间
n
表示将下一行输入读入模式空间
h
复制图案空间以保留空格
sed -n
表示禁止自动打印图案空间 (即仅当 p
出现时才打印)
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 -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 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)
这篇关于具有多个上下文的多种模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!