我对一个xml文件进行了卷曲。输出类似:
name
uuid3 - name
uuid1 - name
uuid2 - name
class
class - uuid3
class - uuid2
class - uuid1
我需要将此模式排序为:
uuid1 - class - name
uuid2 - class - name
uuid3 - class - name
我认为最好的方法是awk
,但所有的解决方案都很好。
非常感谢。
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数组)来关联字段一和字段二。在第二块处理(c==2
)中,打印第二字段、第一字段,并从映射中查找第一字段的值。代码的第一部分删除了查找工作所需的额外空间。
假设"class"是一个文字常量,我们可以将其用作引用,那么这将起作用:
#!/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}"
如果"class"不是一个文字字符串,它可能仍然有一些帮助。抱歉,您在OP 中没有提供太多信息