用这个:

grep -A1 -B1 "test_pattern" file

将在文件中匹配的模式前后产生一行。是否有一种方法不显示行,而是显示指定数量的字符?

我的文件中的行相当大,所以我对打印整行不感兴趣,而只是在上下文中观察匹配。有什么建议吗?


当前回答

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

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

23 _string_and

其他回答

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

这将匹配最多5个字符前后你的模式。-o开关告诉grep只显示匹配项,-E则告诉grep使用扩展正则表达式。请确保在表达式周围加上引号,否则它可能会被shell解释。

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

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

前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

你可以用

awk '/test_pattern/ {
    match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
}' file