2012-09-14 169 views
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.但是,我希望它在item1之前插入。

Idealy,该文件将时的样子:

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会更好。

+3

' ...'是那个正确的......?看起来不像有效的XML。 – TLP

+0

我推荐一个XML解析器,其中大部分应该能够在某个范围内注入一个新元素 –

回答

1

你可以试试这个从file_to_insert假设你的标题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后,将已插入线。

0
sed '/<States>/a\ 
<item4> something something </item4> 
' input-file 
相关问题