重新排序管道分隔字段并在 2 个字段之间进行连接

重新排序管道分隔字段并在 2 个字段之间进行连接

输入:

|Ordernum=8921|mn=03|yr=20|id=869|Name=1|Street=2|City=3|State=4|Zip=5|Country=6|

输出:

8921,03/20,869,1,2,3,4,5,6

我怎样才能做到这一点?

答案1

sed

sed 's/|[^=]*=/,/g; s/|$//; s/,//; s|,|/|2'

或者如果mnyr并不总是第二个和第三个字段(但按该顺序找到):

sed 's@|mn\(=[^|]*\)|yr=@|mnyr\1/@; s/|[^=]*=/,/g; s/|$//; s/,//'

答案2

使用 GNU awk

awk -F\| '{print gensub(/Ordernum=(.*)/,"\\1","g",$2)","gensub(/mn=(.*)/,"\\1","g",$3)"/"gensub(/yr=(.*)/,"\\1","g",$4)","gensub(/id=(.*)/,"\\1","g",$5)","gensub(/Name=(.*)/,"\\1","g",$6)","gensub(/Street=(.*)/,"\\1","g",$7)","gensub(/City=(.*)/,"\\1","g",$8)","gensub(/State=(.*)/,"\\1","g",$9)","gensub(/Zip=(.*)/,"\\1","g",$10)","gensub(/Country=(.*)/,"\\1","g",$11)}'

答案3

Awk解决方案:

awk '{
         for (i = 1; i <= NF; i++)    # iterating through all fields
             if ($i != "") {          # check if field value is not empty
                 c++; sub(/[^=]+=/, "", $i);
                 printf "%s%s", (c > 1? (c == 3? "/" : ",") : ""), $i
             }
             print "" 
     }' FS='|' file

输出:

8921,03/20,869,1,2,3,4,5,6

答案4

使用 GNUawk查找仅包含数字的字段:

awk -v FPAT='[0-9]+' -v OFS=',' '{$2=$2 "/" $3; printf "%s,%s,",$1,$2; for(i=4;i<=NF;i++){ printf "%s%s",$i,i==NF?ORS:OFS}}'  <<< "|Ordernum=8921|mn=03|yr=20|id=869|Name=1|Street=2|City=3|State=4|Zip=5|Country=6|"

FPAT描述图案的外观。在本例中,它仅由数字组成。

OFS是允许使用 进行格式化的输出字段分隔符,

第二场与第三场一起重建。所有其他内容均按原样打印。

相关内容