使用脚本XML添加一个递增的价值属性,每个标签 [英] Adding an incrementing value attribute to every tag in xml using script

查看:192
本文介绍了使用脚本XML添加一个递增的价值属性,每个标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我的XML,这是使用两种AWK递增,sed的添加到每个标签的属性,Perl或纯壳CMD

I want to add an attribute to every tag in my xml, which is incrementing using either awk, sed, perl or plain shell cmd

有关例如:

<tag1 key="123">
  <tag2 abc="xf d"/>
  <tag3 def="d2 32">
   </tag3>
</tag1>

我期待下面的输出

I am expecting the following output

<tag1 key="123" order="1">
  <tag2 abc="xf d" order="2"/>
  <tag3 def="d2 32" order="3">
   </tag3>
</tag1>

如果有可能我不是在寻找任何依赖关系(嫩枝的libxml),纯字符串操作。

If possible I am not looking on any dependencies(Twig,LibXML), pure string manipulation.

推荐答案

通常情况下,你应该使用合适的解析器来处理XML。但在 AWK

Normally you should use a proper parser to process xml. But in awk:

awk 'match($0, /<[^\/>]+/) { \
     $0 = substr($0, 1, RSTART+RLENGTH-1) " order=\"" ++i "\"" \
          substr($0, RSTART+RLENGTH) \
     }; 1'

我找了开放标签(不&GT; /&GT; 部分)每行。如果找到,将字符串为了=我后,而递增 I 。单 1 在最后一行只是一直执行的 AWK 默认动作: {打印$ 0}

I look for a opening tag (without the > or /> part) on every the line. If found, put the string order="i" after it, while incrementing i. The single 1 on the last line just always executes awk's default action: { print $0 }.

我更新了常规的前pression对修改后的输入工作。它只要你有在同一行的多个开放标签失败,等等。

I updated the regular expression to work on your revised input. It fails as soon as you have multiple opening tags on a single line, etc.

这篇关于使用脚本XML添加一个递增的价值属性,每个标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆