我只是给出一部分庞大的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"时输出,并将输出保存到文件中。怎么做?
发布于 2016-06-29 20:03:02
一个解决方案是使用XML,例如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"] --接受所有具有chopper属性的caldata元素等于off;c1[@unit="Hz"] -从该caldata元素中获取具有unit属性等于Hz的c1元素;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我不知道您是否可以使用这样的自定义工具,当然,如果可以,它可以是您的最佳解决方案。
发布于 2016-06-29 20:01:37
这样做可以:
cat file.xml | awk '/chopper="off"/,/calcdata/{print}' | grep 'unit="Hz"' | sed 's/^.*">//;s/<.*$//'第一个命令(awk)只接受包含chopper="off"的块。第二个命令(grep)只接受你想要的数字行。第三个命令(sed)从行中获取数字。
发布于 2016-06-29 20:15:13
由于您使用的是grep,所以我将假设一些*nix和命令行类型的解决方案。
在这种情况下,您可能希望看到类似zorba的内容,它将使用xquery解析输入文档并输出所需的部分。
如果数据中的容器元素为foo,则xquery将包含:
for $c in /foo/caldata
return if ($c/@chopper="on")
then $c else ""https://stackoverflow.com/questions/38108795
复制相似问题