使用sed在文件中插入一些文本

时间:2012-02-13 07:25:19

标签: linux sed

我正在尝试使用SED对CUPS配置文件进行一些更改。

我想要做的是找到以下文字:

# Restrict access to the server...
<Location />
  Order allow, deny

并将其附加到它:

  Allow from all

我已经尝试了sed '/# Restrict access to the server...\n<Location />\n Order allow, deny\n/ a\ Allow from all' etc/cups/cupsd.conf,但我不知道如何逃避&gt;,并且在它前面添加一个反斜杠不起作用。

2 个答案:

答案 0 :(得分:2)

这对你有用:

sed 'N;/<Location \/>\n *Order allow, deny/s//&\n  Allow from all/;P;D' file

或者

sed $'N;/<Location \\/>\\n *Order allow, deny/a\\\nAllow from all\nP;D;' file

实施例

$ sed 'N;/<Location \/>\n *Order allow, deny/s//&\n  Allow from all/;P;D' cups.in
# other stuff here
# Restrict access to the server...
<Location />
  Order allow, deny
  Allow from all
</Location>
stuff

$ sed $'N;/<Location \\/>\\n *Order allow, deny/a\\\n  Allow from all\nP;D;' cups.in
# other stuff here
# Restrict access to the server...
<Location />
  Allow from all
  Order allow, deny
</Location>
stuff

请注意,添加Allow from all的顺序是不同的,尽管我不认为这会使功能有所不同。

答案 1 :(得分:0)

这可能对您有用:

sed '/# Restrict access to the server/{$!N;$!N;s/<Location \/>\n  Order allow, deny$/&\n  Allow from all/}' file

或者这个:

sed ':a;$!{N;ba};s/# Restrict access to the server[^\n]*\n<Location \/>\n  Order allow, deny[^\n]*/&\n  Allow from all/' file

或者很可能是这个(GNU awk?):

sed '/# Restrict access to the server/,+3s/Order allow, deny/&\n  Allow from all/' file