最好使用perl或unix命令来解析此字符串

时间:2011-04-19 20:43:33

标签: perl unix

是否有一个好的unix one liner或perl liner可以格式化这个字符串:

<?xml version="1.0" encoding="UTF-8"?><org.apache.Summary length="200429142" fileCount="197184" dirCount="50" quota="-1" spaceUsed="601287428" spaceQuota="-1"/>

要:

length=200429142
filecount=197184
dirCount=50
quota=-1
spaceUsed=601287428
spaceQuota=-1

5 个答案:

答案 0 :(得分:6)

这是一个单行,为了清晰起见分成不同的行:

perl -MXML::Simple -l \
    -e '$a = XMLin shift; print "$_=$a->{$_}" for ' \
    -e 'qw(length fileCount dirCount quota spaceUsed spaceQuota)' \
    (your XML string here)

这要求您安装XML::Simple模块。

答案 1 :(得分:3)

快速拍摄:这个怎么样?

sed -r 's/.*<org.apache.Summary\s+([^>]+)>/\1/' | tr " " "\n"

答案 2 :(得分:2)

 sed -e 's/.*Summary //;s/\/.*$//' temp|perl -p -e 's/ /\n/g'

length="200429142"
fileCount="197184"
dirCount="50"
quota="-1"
spaceUsed="601287428"
spaceQuota="-1"

如果你想这样做:

sed -e 's/.*Summary //;s/\/.*$//' temp|perl -pi -e 's/ /\n/g'

如果你不需要"那么:

 sed -e 's/.*Summary //;s/\/.*$//' temp|perl -p -e 's/ /\n/g;s/\"//g'
length=200429142
fileCount=197184
dirCount=50
quota=-1
spaceUsed=601287428
spaceQuota=-1

答案 3 :(得分:1)

基于@bmk的精炼版

sed -r 's/<\?.?*\?>//' | sed -r 's/<[a-z\.]+//I' | \
sed -r 's/\/>//' | sed -r 's/ ([a-z]+)="(-?[0-9]+)"/\1=\2\n/Ig'

共使用了4 sed

  1. 删除<?xml?>
  2. 删除<org.apache.Summary
  3. 删除/>
  4. 将XML属性提取为对。

答案 4 :(得分:0)

这应该做你需要的。

perl -0777 -E'given(<>){/\?>/g; say "$1$2" while /(\w+=)"(.*?)"/g}' myfile.xml

<强>输出

length=200429142
fileCount=197184
dirCount=50
quota=-1
spaceUsed=601287428
spaceQuota=-1
相关问题