如何使用sed在文件中的指定行之前插入文本?

如何使用sed在文件中的指定行之前插入文本?

我的文件 /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

相关内容