如何在文本的某一行末尾添加内容
我想在某一行的末尾添加一些内容(有一些给定的字符)。 例如,文本是:
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',它将在该行之后插入一个新行。那不是我想要的。我希望它附加到当前行。
有人可以帮我解决这个问题吗?
多谢!
I want to append something at the end of a certain line(have some given character).
For example, the text is:
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.
Then I want to add "Please help me" at the end of
Line2: Thanks to all who look into my problem
And "Line2"
is the key word. (that is I have to append something by grep this line by key word).
So the text after the script should be:
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.
I know sed
can append something to certain line but, if I use sed '/Line2/a\Please help me'
, it will insert a new line after the line. That is not what I want. I want it to append to the current line.
Could anybody help me with this?
Thanks a lot!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我可能会选择 John 的 sed 解决方案,但是,既然您也询问了 awk:
此输出:
关于其工作原理的解释可能会有所帮助。将
awk
脚本想象如下,左侧为条件,右侧为命令:这两个
awk
子句针对处理的每一行执行。如果该行与正则表达式
^Line2:
匹配(表示行开头的“Line2:”),则可以通过附加所需的字符串 ($0
是读入awk
的整行)。如果该行与空条件匹配(所有行都将与此匹配),则执行 print 。这将输出当前行
$0
。所以你可以看到它只是一个简单的程序,它在必要时修改该行并输出该行,无论修改与否。
此外,即使对于
sed
解决方案,您也可能希望使用/^Line2:/
作为键,这样您就不会选择Line2
在文本中间或Line20
到Line29
、Line200
到Line299
等:I'd probably go for John's
sed
solution but, since you asked aboutawk
as well:This outputs:
An explanation as to how it works may be helpful. Think of the
awk
script as follows with conditions on the left and commands on the right:These two
awk
clauses are executed for every single line processed.If the line matches the regular expression
^Line2:
(meaning "Line2:" at the start of the line), you change$0
by appending your desired string ($0
is the entire line as read intoawk
).If the line matches the empty condition (all lines will match this),
print
is executed. This outputs the current line$0
.So you can see it's just a simple program which modifies the line where necessary and outputs the line, modified or not.
In addition, you may want to use
/^Line2:/
as the key even for ased
solution so you don't pick upLine2
in the middle of the text orLine20
throughLine29
,Line200
throughLine299
and so on:外壳脚本
Shell scripting