如何grep我的xml文件并保存输出?

时间:2016-06-29 19:45:51

标签: xml shell xml-parsing grep

我只是提供巨大的xml文件的一部分

   <caldata chopper="on" gain_1="0" gain_2="0" gain_3="0" impedance="(0,0)">
      <c0 unit="V">0.00000000e+00</c0>
      <c1 unit="Hz">4.00000000e+04</c1>
      <c2 unit="V/(nT*Hz)">8.35950000e-06</c2>
      <c3 unit="deg">-1.17930000e+02</c3>
    </caldata>
    <caldata chopper="on" gain_1="0" gain_2="0" gain_3="0" impedance="(0,0)">
      <c0 unit="V">0.00000000e+00</c0>
      <c1 unit="Hz">5.55810000e+04</c1>
      <c2 unit="V/(nT*Hz)">4.43400000e-06</c2>
      <c3 unit="deg">-1.58280000e+02</c3>
    </caldata>
    <caldata chopper="on" gain_1="0" gain_2="0" gain_3="0" impedance="(0,0)">
      <c0 unit="V">0.00000000e+00</c0>
      <c1 unit="Hz">6.00000000e+04</c1>
      <c2 unit="V/(nT*Hz)">3.63180000e-06</c2>
      <c3 unit="deg">-1.67340000e+02</c3>
    </caldata>
    <caldata chopper="off" gain_1="0" gain_2="0" gain_3="0" impedance="(0,0)">
      <c0 unit="V">0.00000000e+00</c0>
      <c1 unit="Hz">4.00000000e-01</c1>
      <c2 unit="V/(nT*Hz)">1.07140000e-02</c2>
      <c3 unit="deg">1.48080000e+02</c3>
    </caldata>
    <caldata chopper="off" gain_1="0" gain_2="0" gain_3="0" impedance="(0,0)">
      <c0 unit="V">0.00000000e+00</c0>
      <c1 unit="Hz">5.55800000e-01</c1>
      <c2 unit="V/(nT*Hz)">1.33250000e-02</c2>
      <c3 unit="deg">1.39110000e+02</c3>
    </caldata>
    <caldata chopper="off" gain_1="0" gain_2="0" gain_3="0" impedance="(0,0)">
      <c0 unit="V">0.00000000e+00</c0>
      <c1 unit="Hz">7.72300000e-01</c1>
      <c2 unit="V/(nT*Hz)">1.57750000e-02</c2>
      <c3 unit="deg">1.29560000e+02</c3>

我试过这样的

grep '<c1 unit="Hz"' *.xml | cut -f2 -d">"|cut -f1 -d"<"

工作正常我真正想要的只是在输出时  caldata chopper="off" 并将我的输出保存到文件。 怎么做?

3 个答案:

答案 0 :(得分:3)

解决方案是使用XML grep,例如xgrep。我在自己的机器上自己试了一下并得到了这个:

$ xgrep -t -x '//caldata[@chopper="off"]/c1[@unit="Hz"]/text()' test.xml 
4.00000000e-01
5.55800000e-01
7.72300000e-01

秘密是XPath表达式:

  • //caldata[@chopper="off"] - 将所有caldata元素与chopper属性等于off;
  • c1[@unit="Hz"] - 来自caldata个元素,获取c1unit属性的元素等于Hz;
  • text() - 来自那些c1元素,只获取文字内容。

要将其保存到输出文件,只需使用shell中的>重定向器即可。我们只需要在命令后添加它,然后添加文件名以获得输出:

$ xgrep -t -x '//caldata[@chopper="off"]/c1[@unit="Hz"]/text()' test.xml  > output.xml
$ cat output.xml 
4.00000000e-01
5.55800000e-01
7.72300000e-01

我不知道你是否可以使用这样的自定义工具,但如果可以的话,它可能是你最好的解决方案。

答案 1 :(得分:2)

这样做:

cat file.xml | awk '/chopper="off"/,/calcdata/{print}' | grep 'unit="Hz"' | sed 's/^.*">//;s/<.*$//'

第一个命令(awk)仅包含包含chopper="off"的块。第二个命令(grep)仅使用包含所需数字的行。第三个命令(sed)从行中获取数字。

答案 2 :(得分:0)

由于你正在使用grep,我将假设有一些* nix和命令行类型的解决方案

在这种情况下,您可能希望查看类似zorba的内容,它将使用xquery解析您的输入文档并输出您想要的部分。

如果数据中的容器元素是foo,则xquery将包含:

'Five Thousand Fifty'