如何在将输出重定向到文件时标记匹配的 GREP 字符串

Raf*_*fal 3 scripts regex grep output text-processing

我正在尝试使用 grep 在文件中查找所有匹配的字符串,并将它们在行的上下文中输出到另一个文件,同时在匹配的每一侧添加某种标记(最好是两个星号)。

例如,我有input.txt以下比赛的文件:

Dog walks in the park
Man runs in the park
Man walks in the park
Dog runs in the park
Dog is still
They run in the park
Woman runs in the park
Run Code Online (Sandbox Code Playgroud)

然后,我通过重定向到文件进行 grep 搜索:

grep -P ' runs? ' input.txt > output.txt
Run Code Online (Sandbox Code Playgroud)

它创建output.txt具有以下竞赛的文件:

Man runs in the park
Dog runs in the park
They run in the park
Woman runs in the park
Run Code Online (Sandbox Code Playgroud)

我想做的是获得该输出:

Man **runs** in the park
Dog **runs** in the park
They **run** in the park
Woman **runs** in the park
Run Code Online (Sandbox Code Playgroud)

也就是说,为上下文中的每个匹配项在该匹配项周围添加两个星号。

我知道我只能通过添加-o选项来获得匹配项:

grep -P ' runs? ' input.txt > output.txt
Run Code Online (Sandbox Code Playgroud)

但我需要在上下文中查看它们。

我也知道我可以通过运行以下命令在交互式会话中突出显示这些匹配项:

GREP_OPTIONS='--color=auto'
Run Code Online (Sandbox Code Playgroud)

但是我在 bash 脚本中使用了 grep,所以它对我没有用。

所以我想知道是否有任何方法可以直接使用 grep 在输出文件中标记这些匹配项。我知道我以后可能可以通过管道将 grep 输出传递到不同的命令来实现这一点,但我更愿意使用一些 grep 选项。是否可以?如果没有,在将 grep 与其他工具结合使用时,实现我想要的输出的最直接方法是什么?

kos*_*kos 5

您想使用其他工具来执行替换,例如sed

sed -n 's/ \(runs\?\) / **\1** /p' input.txt > output.txt
Run Code Online (Sandbox Code Playgroud)

或 Perl:

perl -ne 's/ (runs?) / **$1** /&&print' input.txt > output.txt
Run Code Online (Sandbox Code Playgroud)