用这个:

grep -A1 -B1 "test_pattern" 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。

其他回答

使用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。

如果使用ripgreg,你会这样做:

grep -E -o ".{0,5}test_pattern.{0,5}" test.txt 

你的意思是这样的:

grep -o '.\{0,20\}test_pattern.\{0,20\}' file

?

这将在test_pattern的两侧打印最多20个字符。\{0,20\}符号类似于*,但指定了0到20次重复,而不是0或更多。-o表示只显示匹配本身,而不是整行。

前3个字符,后4个字符

$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and

您可以使用regexp grep来查找+第二个grep来突出显示

echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}' | grep string

23 _string_and