【发布时间】:2013-06-25 19:15:20
【问题描述】:
我最初的问题是能够在配置文件中特定块的末尾添加一行。
############
# MY BLOCK #
############
VALUE1 = XXXXX
VALUE2 = YYYYY
MYNEWVALUE = XXXXX <<< I want to add this one
##############
# MY BLOCK 2 #
##############
为此,我使用了以下 sed 脚本,它可以完美运行(在另一篇文章中找到):
sed -i -e "/# MY BLOCK #/{:a;n;/^$/!ba;i\MYNEWVALUE = XXXXX" -e '}' myfile
这在 shell 脚本中执行时效果很好,但我无法直接在交互式 shell 中使用它(它给了我一个错误:“!ba event not found”)。为了解决这个问题,我尝试在 '!ba' 之前添加 '\' 但现在它给了我另一个错误,告诉我 '\' 是一个未知命令。
谁能解释我在上述问题上的错误在哪里以及这个脚本是如何工作的?
这是我的理解:
-i : insert new line (i think the first one is useless, am i right?)
-e : execute this sed script (don't understand why there is a second one at the end to close the })
:a : begin a loop
n : read each line with the pattern ^$ (empty lines)
! : reverse the loop
ba : end of the loop
谢谢!
【问题讨论】:
-
-i是--in-place的缩写(用修改后的内容替换输入文件),-e是--expression的缩写。阅读man sed会向您揭示(以及更多)。 -
我做到了,谢谢你的回复。我只想知道 sed 是如何工作的,因为您可以看到我的 -i 和 -e 在 man 描述附近。