如何将一个文件插入到另一个文件的标记位置

How to insert one file into another file's marked place

目标文件和源文件都是xml类型文件。

我很难使用 sed,因为它不能很好地处理特殊字符,而那些 xml 中到处都是。

我研究过 awk 有一种方法,这是我的问题,因为我很难使用 awk

编辑:

主 xml 文件标记位置:

<?xml version="1.0" encoding="utf-8"?>
<ip>
<?processing instructions?>
<lista>

<!--> EKOLOGIA +5 <-->
<kategoria nazwa="EKO" thumb="/home/xvision/ip/swf/EKO/eko.png">
</kategoria>
<!-- KONIEC PAKIETU <-->

<!--temp-->
</lista>
</ip>

要包含在主文件中的文件(第二个 xml):

<!--> PAKIET FUN 50 GIER <-->
<kategoria nazwa="EDU" thumb="/home/xvision/ip/swf/EDU/edu.png">
</kategoria>

最终文件:

<?xml version="1.0" encoding="utf-8"?>
<ip>
<?processing instructions?>
<lista>

<!--> EKOLOGIA +5 <-->
<kategoria nazwa="EKO" thumb="/home/xvision/ip/swf/EKO/eko.png">
</kategoria>
<!-- KONIEC PAKIETU <-->

<!--> PAKIET FUN 50 GIER <-->
<kategoria nazwa="EDU" thumb="/home/xvision/ip/swf/EDU/edu.png">
</kategoria>
</lista>
</ip>

万一没有人可以使用 XML 感知工具为您提出解决方案,这可能就是您所需要的:

$ awk '
    NR==FNR { lines = (NR>1 ? lines ORS : "") [=10=]; next }
    [=10=] == "<!--temp-->" { [=10=] = lines }
    { print }
' second.xml main.xml
<?xml version="1.0" encoding="utf-8"?>
<ip>
<?processing instructions?>
<lista>

<!--> EKOLOGIA +5 <-->
<kategoria nazwa="EKO" thumb="/home/xvision/ip/swf/EKO/eko.png">
</kategoria>
<!-- KONIEC PAKIETU <-->

<!--> PAKIET FUN 50 GIER <-->
<kategoria nazwa="EDU" thumb="/home/xvision/ip/swf/EDU/edu.png">
</kategoria>
</lista>
</ip>

这应该有效

$ sed -i -e '/<!--temp-->/{r file.insert' -e 'd}' file.main

在标记处插入文件并删除标记行,原地替换修改主文件。

-e 选项定义了一个脚本,我们可以多次使用它吗,这里它两次用于两个单独的操作,匹配行插入文件,第二个块删除(匹配的)行。注意作为脚本边界的单引号。