0

我有一个像这样的文本流 ,我想从中得到一个输出,比如 输入中有很多行都是不可写的。
<device nid="05023CA70900" id="1" fblock="-1" type="switch" name="Appliance Home" brand="Google" active="false" energy_lo="427" />
<device nid="0501C1D82300" id="2" fblock="-1" type="switch" name="TELEVISION Home" brand="Google" active="pending" energy_lo="3272" />


05023CA70900@@1@@-1@@switch@@Appliance Home@@Google@@false@@427 0501C1D82300@@2@@-1@@switch@@TELEVISION Home@@Google@@pending@@3272

我们如何使用 awk 或 sed 来实现这一点?

4

3 回答 3

1

它在 perl 中非常简单。那么为什么不使用 perl 呢?

perl -lne 'push @a,/\"([\S]*)\"/g;print join "@@",@a;undef @a' your_file

样品测试:

> cat temp
<device nid="05023CA70900" id="1" fblock="-1" type="switch" name="Appliance Home" brand="Google" active="false"  energy_lo="427" />  
<device nid="0501C1D82300" id="2" fblock="-1" type="switch" name="TELEVISION Home" brand="Google" active="pending"  energy_lo="3272" />  
> perl -lne 'push @a,/\"([\S]*)\"/g;print join "@@",@a;undef @a' temp
05023CA70900@@1@@-1@@switch@@Google@@false@@427
0501C1D82300@@2@@-1@@switch@@Google@@pending@@3272
>
于 2013-07-16T12:43:51.747 回答
1

以下 awk 应该可以工作:

awk -F '"' '$1 == "<device nid=" { printf("%s@@%s@@%s@@%s@@%s@@%s@@%s@@%s\n", 
                    $2, $4, $6, $8, $10, $12, $14, $16)}' file

PS:使用 awk/sed 解析 XML 并不总是最好的方法。

于 2013-07-16T09:57:48.003 回答
0
awk -F\" -v OFS="@@" '/^<device nid=/ { print $2, $4, $6, $8, $10, $12, $14, $16 }' file

或更一般地说:

awk -F\" '/^<device nid=/ {for (i=2;i<=NF;i+=2) printf "%s%s",(i==2?"":"@@"),$i; print ""}' file

在您的评论中解决您的问题:如果您可以在前面有一个标签<device nid

awk -F\" '/^\t?<device nid=// ...'

如果您的意思是别的,请更新您的问题并提供更具代表性的意见。

于 2013-07-16T12:33:34.530 回答