使用Sed或awk合并数据的格式

时间:2018-01-31 19:01:15

标签: awk sed

我有以下格式的数据 Room : L1, Name : Test, DOB : 2017-10-12, Section : ABC, Name : BTest2, Status : APPROVE, DOB : 2017-10-12, Rule : forward, Comment : Testing comment, Room : L2, Name : Test2, DOB : 2017-10-11, Rule : Backward,

我正在尝试以下面的格式输出 Room : L1,Name : Test,DOB : 2017-10-12,Section : ABC, Room : L1,Name : BTest2,Status : APPROVE,DOB : 2017-10-12,Rule : forward,Comment : Testing comment, Room : L2,Name : Test2,DOB : 2017-10-11,Rule : Backward,

我尝试使用awk和sed来格式化数据,但由于模式不是很一致,我无法这样做。反正是基于Name的出现而做的。在下面的示例中,我使用了Name和Comment,因此它失败了。

awk '/^Room/{s=$0} /^Name/ && match(p,/^Comment/){$0=sprintf("%s%s%s",s,ORS,$0)} {print;p=$0}' test.txt | sed ':a;/Comment/!{N;s/\n//g;ba}'

非常感谢帮助。

3 个答案:

答案 0 :(得分:3)

Awk 解决方案:

awk '/^Room/{ if (R){ print ""; delete keys } R=$0; k=$3 }
     /^Name/{ keys[k $1]++ }
     { printf "%s%s", (keys[k $1] > 1? ORS R : ""), $0 }
     END{ print "" }' file

输出:

Room : L1,Name : Test,DOB : 2017-10-12,Section : ABC,
Room : L1,Name : BTest2,Status : APPROVE,DOB : 2017-10-12,Rule : forward,Comment : Testing comment,
Room : L2,Name : Test2,DOB : 2017-10-11,Rule : Backward,

答案 1 :(得分:3)

awk '/^Room/          {room=$0;                  next}
     NR==2 && /^Name/ {printf("%s%s",room,$0);   next}
     NR>2  && /^Name/ {printf("\n%s%s",room,$0); next}
     {printf("%s",$0)}
     END{print ""}' file

输出:

Room : L1,Name : Test,DOB : 2017-10-12,Section : ABC,
Room : L1,Name : BTest2,Status : APPROVE,DOB : 2017-10-12,Rule : forward,Comment : Testing comment,
Room : L2,Name : Test2,DOB : 2017-10-11,Rule : Backward,

答案 2 :(得分:1)

这可能适合你(GNU sed):

sed -r '/^Room/{:a;N;s/^((.*, )(Name).*\n)\3/\1\2\3/;tb;/\nRoom/!s/\n/ /;ta;:b;P;D}' file

这会将Room之间的行聚集到一行中,然后插入换行符和Room字段,其中有多个Name字段。