![如何使用sed在文件中的指定行之前插入文本?](https://linux22.com/image/191505/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8sed%E5%9C%A8%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E6%8C%87%E5%AE%9A%E8%A1%8C%E4%B9%8B%E5%89%8D%E6%8F%92%E5%85%A5%E6%96%87%E6%9C%AC%EF%BC%9F.png)
我的文件 /usr/share/glib-2.0/schemas/org.gnome.Vino.gschema.xml 的最后几行如下所示:
<key name='notify-on-connect' type='b'>
<summary>Notify on connect</summary>
<description>
If true, show a notification when a user connects to the system.
</description>
<default>true</default>
</key>
</schema>
</schemalist>
现在我想在该行前添加几行,以达到以下效果:
<key name='notify-on-connect' type='b'>
<summary>Notify on connect</summary>
<description>
If true, show a notification when a user connects to the system.
</description>
<default>true</default>
</key>
<key name='enabled' type='b'>
<summary>Enable remote access to the desktop</summary>
<description>
If true, allows remote access to the desktop via the RFB
protocol. Users on remote machines may then connect to the
desktop using a VNC viewer.
</description>
<default>false</default>
</key>
</schema>
</schemalist>
我现在需要编写一个shell脚本,通过sed命令来实现上述效果,我写的如下所示:
sed -i "/\</schema\>/i \ <key name='enabled' type='b'>\n <summary>Enable remote access to the desktop</summary>\n <description>\n If true, allows remote access to the desktop via the RFB\n protocol. Users on remote machines may then connect to the\n desktop using a VNC viewer.\n </description>\n <default>false</default>\n </key>\n" /usr/share/glib-2.0/schemas/org.gnome.Vino.gschema.xml
但执行后并没有添加内容。我该如何用sed来写才能达到我上面的效果呢?顺便说一句:</schema>行前面有两个空格。
答案1
该i\
命令采用由反斜杠转义的文字硬编码换行符,而不是\n
使用以下模板在输入文件中进行更改。
sed -i.BAK -e '
/<\/schema>/i\
<key name='\''enabled'\'' type='\''b'\''>\
<summary>Enable remote access to the desktop</summary>\
<description>\
If true, allows remote access to the desktop via the RFB\
protocol. Users on remote machines may then connect to the\
desktop using a VNC viewer.\
</description>\
<default>false</default>\
</key>
' /usr/share/glib-2.0/schemas/org.gnome.Vino.gschema.xml
## now do a diff between these:
diff /usr/share/glib-2.0/schemas/org.gnome.Vino.gschema.xml /usr/share/glib-2.0/schemas/org.gnome.Vino.gschema.xml.BAK