使用这个:
grep -A1 -B1 "test_pattern" file
Run Code Online (Sandbox Code Playgroud)
将在文件中匹配的模式之前和之后生成一行.有没有办法显示不是行而是指定数量的字符?
我文件中的行非常大,所以我对打印整行不感兴趣,而只是在上下文中观察匹配.有关如何做到这一点的任何建议?
ДМИ*_*КОВ 159
前3个字符后4个字符
$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and
Run Code Online (Sandbox Code Playgroud)
eks*_*kse 98
grep -E -o ".{0,5}test_pattern.{0,5}" test.txt
Run Code Online (Sandbox Code Playgroud)
这将在您的模式之前和之后匹配最多5个字符.-o开关告诉grep只显示匹配,-E使用扩展正则表达式.确保在表达式周围加上引号,否则shell可能会解释它.
ami*_*t_g 37
你可以用
awk '/test_pattern/ {
match($0, /test_pattern/); print substr($0, RSTART - 10, RLENGTH + 20);
}' file
Run Code Online (Sandbox Code Playgroud)
rua*_*akh 24
你的意思是,像这样:
grep -o '.\{0,20\}test_pattern.\{0,20\}' file
Run Code Online (Sandbox Code Playgroud)
?
这将在两侧打印多达20个字符test_pattern.该\{0,20\}标记是一样*的,但指定零到二十重复,而不是零或more.The -o说,只显示了比赛本身,而不是整条生产线.