用这个:
grep -A1 -B1 "test_pattern" file
将在文件中匹配的模式前后产生一行。是否有一种方法不显示行,而是显示指定数量的字符?
我的文件中的行相当大,所以我对打印整行不感兴趣,而只是在上下文中观察匹配。有什么建议吗?
用这个:
grep -A1 -B1 "test_pattern" file
将在文件中匹配的模式前后产生一行。是否有一种方法不显示行,而是显示指定数量的字符?
我的文件中的行相当大,所以我对打印整行不感兴趣,而只是在上下文中观察匹配。有什么建议吗?
当前回答
你的意思是这样的:
grep -o '.\{0,20\}test_pattern.\{0,20\}' file
?
这将在test_pattern的两侧打印最多20个字符。\{0,20\}符号类似于*,但指定了0到20次重复,而不是0或更多。-o表示只显示匹配本身,而不是整行。
其他回答
grep -E -o ".{0,5}test_pattern.{0,5}" test.txt
这将匹配最多5个字符前后你的模式。-o开关告诉grep只显示匹配项,-E则告诉grep使用扩展正则表达式。请确保在表达式周围加上引号,否则它可能会被shell解释。
您可以使用regexp grep来查找+第二个grep来突出显示
echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}' | grep string
23 _string_and
在gawk中,你可以使用match函数:
x="hey there how are you"
echo "$x" |awk --re-interval '{match($0,/(.{4})how(.{4})/,a);print a[1],a[2]}'
ere are
如果你可以使用perl,更灵活的解决方案:下面将在模式之前打印三个字符,然后是实际的模式,然后在模式之后打印5个字符。
echo hey there how are you |perl -lne 'print "$1$2$3" if /(.{3})(there)(.{5})/'
ey there how
这也可以应用于单词,而不仅仅是字符。下面将在实际匹配的字符串之前打印一个单词。
echo hey there how are you |perl -lne 'print $1 if /(\w+) there/'
hey
下面将在模式后面打印一个单词:
echo hey there how are you |perl -lne 'print $2 if /(\w+) there (\w+)/'
how
下面将在模式之前打印一个单词,然后是实际单词,然后是模式之后打印一个单词:
echo hey there how are you |perl -lne 'print "$1$2$3" if /(\w+)( there )(\w+)/'
hey there how
你可以用
awk '/test_pattern/ {
match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
}' file
使用ugrep,你可以用选项-o(——only-matching)指定-ABC context,在匹配之前和/或之后显示额外的上下文字符的匹配,将匹配加上指定的-ABC宽度内的上下文。例如:
ugrep -o -C30 pattern testfile.txt
给:
1: ... long line with an example pattern to match. The line could...
2: ...nother example line with a pattern.
在终端上,同样的颜色高亮显示: 一行中的多个匹配项显示为[+nnn more]: 或者使用选项-k(——column-number)分别显示每个对象的上下文和列号: 上下文宽度是显示的Unicode字符的数量(UTF-8/16/32),而不仅仅是ASCII。