我想在某一行的末尾添加一些东西(有一些给定的字符).例如,文本是:
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.
Run Code Online (Sandbox Code Playgroud)
然后我想在最后添加"请帮助我"
Line2: Thanks to all who look into my problem
Run Code Online (Sandbox Code Playgroud)
这"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.
Run Code Online (Sandbox Code Playgroud)
我知道sed
可以在某些行上附加某些内容但是,如果我使用sed '/Line2/a\Please help me'
它,它将在该行之后插入一个新行.那不是我想要的.我希望它附加到当前行.
有人可以帮帮我吗?
非常感谢!
pax*_*blo 16
我可能会选择约翰的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}'
Run Code Online (Sandbox Code Playgroud)
这输出:
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.
Run Code Online (Sandbox Code Playgroud)
关于它如何工作的解释可能会有所帮助.将awk
脚本视为左侧的条件和右侧的命令:
/^Line2:/ {$0=$0" Please help me"}
{print}
Run Code Online (Sandbox Code Playgroud)
awk
对处理的每一行执行这两个子句.
如果该行与正则表达式匹配^Line2:
(在行的开头表示"Line2:"),则$0
通过附加所需的字符串($0
整行读入awk
)进行更改.
如果该行匹配空条件(所有行将与此匹配),print
则执行.这输出当前行$0
.
所以你可以看到它只是一个简单的程序,可以根据需要修改行,并输出行,修改与否.
此外,/^Line2:/
即使是sed
解决方案,您也可能希望将其用作键,这样您就不会Line2
在文本中间或Line20
通过Line29
,Line200
通过Line299
等接收:
sed '/^Line2:/s/$/ Please help me/'
Run Code Online (Sandbox Code Playgroud)