在模式搜索的同一行插入带有sed的文本

dar*_*men 7 sed

例如,如果我有这个文件:

The green horse is blue localhost
my pants is dirty localhost
your eyes is so beautiful localhost
The best area is localhost
Run Code Online (Sandbox Code Playgroud)

我希望在每次'localhost'模式搜索后在此文件中添加文本(192.168.25.50).

  • 我不想创建新行
  • 我不想在线的每一端插入,而是在模式之后插入
  • 我不想使用awk,我需要知道sed命令是否可以执行此操作

的确,我的结果必须如此:

The green horse is blue localhost 192.168.25.50
my pants is dirty localhost 192.168.25.50
your eyes is so beautiful localhost 192.168.25.50
The best area is localhost 192.168.25.50
Run Code Online (Sandbox Code Playgroud)

很多sed问题都存在,但都有一个特定的上下文,无法解决我的简单和基本问题.我已经可以在同一个文件中的模式之后插入文本但从不在同一行中.

你能解释一下如何在sed命令本身使用的模式的同一行中插入sed命令吗?

Cyr*_*rus 17

使用GNU sed:

sed 's/\blocalhost\b/& 192.168.25.50/' file
Run Code Online (Sandbox Code Playgroud)

\b:零宽度字边界

&:指的是模式空间中匹配的那部分

如果要"就地"编辑文件,请使用sed选项-i.