我想在某行的末尾添加一些内容(具有某些给定的字符)。
例如,文本为:

Line1:  I just want to make clear of the problem
Line2:  Thanks to all who look into my problem
Line3:  How to solve the problem?
Line4:  Thanks to all.


然后,我想在末尾添加“请帮助我”

Line2:  Thanks to all who look into my problem


"Line2"是关键字。 (也就是说,我必须通过grep在关键字这一行中附加一些内容)。

因此,脚本后的文本应为:

Line1:  I just want to make clear of the problem
Line2:  Thanks to all who look into my problem Please help me
Line3:  How to solve the problem?
Line4:  Thanks to all.


我知道sed可以将某些内容追加到某些行,但是,如果使用sed '/Line2/a\Please help me',它将在该行之后插入新行。那不是我想要的。我希望它附加到当前行。

有人可以帮我吗?

非常感谢!

最佳答案

我可能会去寻求John的sed解决方案,但是,由于您也询问了awk

$ echo 'Line1:  I just want to make clear of the problem
Line2:  Thanks to all who look into my problem
Line3:  How to solve the problem?
Line4:  Thanks to all.' | awk '/^Line2:/{$0=$0" Please help me"}{print}'


输出:

Line1:  I just want to make clear of the problem
Line2:  Thanks to all who look into my problem Please help me
Line3:  How to solve the problem?
Line4:  Thanks to all.


关于它如何工作的解释可能会有所帮助。考虑awk脚本,其条件如下,左边为条件,右边为命令:

/^Line2:/ {$0=$0" Please help me"}
          {print}


这两个awk子句在处理的每一行中执行。

如果该行与正则表达式^Line2:匹配(在行的开头表示“ Line2:”),则可以通过附加所需的字符串来更改$0$0是读入awk的整行)。

如果该行匹配空条件(所有行都将匹配此条件),则执行print。这将输出当前行$0

因此,您可以看到它只是一个简单的程序,该程序可以在必要时修改行并输出行,无论是否修改。



此外,即使对于/^Line2:/解决方案,您可能也想将sed用作键,这样您就不会在文本中间或Line2Line20Line29Line200等:

sed '/^Line2:/s/$/ Please help me/'

关于shell - 如何在文本的特定行的末尾附加内容,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3553556/

10-10 05:25