如何使用shell脚本将文本附加到文件中的特定行?

smy*_*dsh 3 linux shell sed

我有一个文本文件(file.txt),其内容类似于:

foo1 3464 
foo2 3696 
foo3 4562 
Run Code Online (Sandbox Code Playgroud)

它包含过程和相应的PID.

根据PID,我想使用shell脚本,在这个文件中追加一个字符串(运行/不运行).

例如,在上面的文件中,对于包含PID 3696的行,我想在末尾添加一个字符串"running",以便该文件变为:

foo1 3464 
foo2 3696 running
foo3 4562 
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Lev*_*sky 10

$ sed '/3696/ s/$/running/' file.txt 
foo1 3464 
foo2 3696 running
foo3 4562 
Run Code Online (Sandbox Code Playgroud)

要么

$ sed 's/3696/& running/' file.txt 
foo1 3464 
foo2 3696 running 
foo3 4562 
Run Code Online (Sandbox Code Playgroud)

添加-i选项以将更改保存回原点file.txt.

  • @ smya.dsh`sed'3s/$/running /'file.txt` (3认同)