我需要有关使用awk (更好)、sed或perl的解决方案的帮助。解决方案应该在bash脚本中进行交互。这是我的问题,我需要在ant build文件目标的目标中插入一行,如下所示:
<target name="-AAAA" unless="non_AAAA_buildpackage">
<antcall target="init"/>
many antcall lines
</target>
<target name="-XXXX" unless="non_XXXX_buildpackage">
<antcall target="init"/>
many antcall lines here
The line should be inserted here as <antcall target="ZZZZ"/>
</target>
<target name="-BBBB" unless="non_BBBB_buildpackage">
<antcall target="init"/>
many antcall lines here
</target>
many targets here as this is a large file请注意,该build.xml文件中有许多目标名称,但name="XXXX"始终是唯一的。所有其他目标的结束分隔符与</target>相同。请注意,应该在行之前插入行. </target>请注意,build.xml是一个包含多个目标的泻湖文件,单词“name=”-XXXX是唯一的,但不是"-XXXX"
发布于 2012-08-22 08:56:27
简单的Perl解决方案:使用一个标志$inside来告诉您是否在所需的目标中:
perl -pe ' $inside = 1 if /<target name="-XXXX"/;
print qq( <antcall target="ZZZZ"/>\n) if $inside and m{</target>};
$inside = 0 if m{</target>};
' 1.xml或者,使用XML::LibXML包装器XML::XSH2
open 1.xml ;
insert chunk { qq( <antcall target="ZZZZ"/>\n) } append //target[@name="-XXXX"] ;
save ;发布于 2012-08-22 08:59:37
用GNU sed
infile含量
<target name="-XXXX" unless="non_XXXX_buildpackage">
<antcall target="init"/>
...............
<antcall target="YYYY"/>
<antcall target="ZZZZ"/> **###The line should be inserted here**
</target>
<target name="-YYYY" unless="non_XXXX_buildpackage">
<antcall target="init"/>
...............
<antcall target="YYYY"/>
<antcall target="ZZZZ"/> **###The line should be inserted here**
</target>script.sed含量
/^<target[ \t]\+name="-XXXX"/,/^<\/target>/ {
/^<\/target>/ { i\
Your line
}
}运行它就像:
sed -f script.sed infile产出如下:
<target name="-XXXX" unless="non_XXXX_buildpackage">
<antcall target="init"/>
...............
<antcall target="YYYY"/>
<antcall target="ZZZZ"/> **###The line should be inserted here**
Your line
</target>
<target name="-YYYY" unless="non_XXXX_buildpackage">
<antcall target="init"/>
...............
<antcall target="YYYY"/>
<antcall target="ZZZZ"/> **###The line should be inserted here**
</target>发布于 2012-08-22 09:01:09
这在sed实用程序中是可行的:
sed -i -e '/-XXXX/,/<\/target>/s/<\/target>/NEWLINEINSERTEDHERE\n<\/target>/' infile我们告诉sed只考虑文件中正确的<target>...</target>部分,然后用添加的行和</target>替换</target>
https://stackoverflow.com/questions/12069217
复制相似问题