0

我想编写一个要在终端中执行的脚本。

我正在编辑 xml 文件,我想在检测到 xml 列的头部后添加一个或多个字符串。

这是一个示例 xml

bunch of line
more unimportant lines
and they can very in number
<States>
<item1> something something </item1>

<item2> something something </item1>

<item3> something something </item1>
</states>

现在我想添加第 4 项。但是,我希望将其插入第 1 项之前。

理想情况下,该文件应如下所示:

bunch of line
more unimportant lines
and they can very in number
and even some lines were added here
and here
and here
<States>
<item4> something something </item1>
<item1> something something </item1>

<item2> something something </item1>

<item3> something something </item1>
</states>

请注意,顶部添加了与代码无关的其他内容。这些是将要进入的评论。

我愿意在 perl 中这样做,但 shell 会更好。

4

2 回答 2

1

假设你的标题States是固定的,你可以试试这个

$ tlines=`wc -l your_file | cut -f1  -d ' '`
$ lno=`grep -n "<States>"  your_file | cut -f1 -d ':'`
$ head -${lno} your_file > your_file.tmp
$ cat file_to_insert >> your_file.tmp
$ tail -`expr ${tlines} - ${lno}` your_file >> your_file.tmp

在此之后your_file.tmp将插入来自file_to_insert.

于 2012-09-14T19:03:35.410 回答
0
sed '/<States>/a\
<item4> something something </item4>
' input-file
于 2012-09-14T19:34:16.687 回答