【问题标题】:How to add a string(s) after a specific string is read?读取特定字符串后如何添加字符串?
【发布时间】:2012-09-07 22:57:27
【问题描述】:

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

我正在编辑 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>

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

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

【问题讨论】:

  • &lt;item2&gt; ... &lt;/item1&gt; 对吗...?看起来不像是有效的 xml。
  • 我推荐一个 XML 解析器,其中大部分应该能够在某个范围内注入新元素

标签: perl bash shell unix terminal


【解决方案1】:
sed '/<States>/a\
<item4> something something </item4>
' input-file

【讨论】:

    【解决方案2】:

    假设你的标题 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-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-21
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多