2016-08-02 52 views
0

我在一个xml文件上做一个curl。 像输出:解析输出如id:name/class:id to id:class:name with bash awk

name 
    uuid3 - name 
    uuid1 - name 
    uuid2 - name 
class 
    class - uuid3 
    class - uuid2 
    class - uuid1 

我需要理清这种模式,如:

uuid1 - class - name 
uuid2 - class - name 
uuid3 - class - name 

我认为做的东西,最好的办法是awk,但所有的解决方案都不错。

非常感谢。

+2

中提供很多信息您是否有任何代码? – Nunchy

+0

你说得对,awk是这样做的最好方法。阅读由Arnold Robbins撰写的第4版Effective Awk Programming一书。 –

回答

4

awk来救援!

$ awk 'BEGIN{OFS=FS=" - "} 
      {gsub(/ /,"",$1); gsub(/ /,"",$2)} 
     c==1{a[$1]=$2} 
     c==2{print $2,$1,a[$2]} 
     NF==1{c++}' file 

uuid3 - class - name 
uuid2 - class - name 
uuid1 - class - name 

条目的顺序基于第二块。

说明

'C' 是块计数,当仅存在一个字段(报头)递增。在处理第一个块(c==1)时,它会创建一个映射(awk数组)来关联字段1和2。在第二个程序段处理(c==2)中打印第二个字段,第一个字段并从地图中查找第一个字段的值。代码的第一部分删除了查找工作的额外空间。

+0

肯定比我的解决方案更有说服力。 – Nunchy

+0

waow <3 thx很多 – Moker

+0

你能否详细解释一下我请的行:c == 1 {a [$ 1] = $ 2},c == 2 {print a [$ 2],$ 1,$ 2},NF == 1 {C++}?谢谢 – Moker

0

假设“阶级”是一个常量,我们可以用它作为参考,那么这会工作:

#!/bin/bash 

str=" 
name 
    uuid1 - one 
    uuid2 - two 
    uuid3 - three 
class 
    class - uuid1 
    class - uuid2 
    class - uuid3 
" 

# Get all lines where the first token is 'class' 
class=`echo -e "${str}" | grep -P "\tclass"` 

# Count all of the lines... 
lines=`echo -e "${class}" | wc -l` 

echo -e "lines = ${lines}\n" 

strout= 

# Loop through the result and extract each individual line... 
l=1 
while [ $l -le $lines ]; do 
    line=`echo -e "${class}" | head -n ${l} | tail -n 1` 

    # Now, token 3 will be the unique uuid token... 
    uuid=`echo -e "$line" | awk '{print $3}'` 

    # We can use this unique uuid to reference the name lines... 
    n=`echo -e "${str}" | grep -P "\t$uuid" | awk '{print $3}'` 

    strout="${strout}\n${uuid} - class - ${n}" 

    l=$((l+1)) 
done 

echo -e "${strout}" 

如果“阶级”是不是一个文本字符串,它可能仍然是一些帮助。对不起,您没有在OP