我的输入是:
group;|line1_1|line2_2|line3_3
我想提取信息行1,行2,行3,如下所示: line1,line2,line3
我已经尝试使用以下命令但无法执行:
LINE="group;|line1_1|line2_2|line3_3"; echo $LINE | awk -F ";" '{print $2}' | awk -F "|" '{for(i=1;i<=NF;++i){print $i | system("cut -d _ -f1")}}'
答案 0 :(得分:1)
考虑到您的实际Input_file与所示示例相同。您能不能试一下。
awk -F'|' '{for(i=2;i<=NF;i++){sub(/_.*/,"",$i);val=val?val OFS $i:$i};print val;val=""}' OFS="," Input_file
第二个解决方案: :此处仅使用sub
中的gsub
和awk
。
awk '{sub(/^[^|]*\|/,"");gsub(/_[0-9]\|/,",");sub(/_[0-9]$/,"")} 1' Input_file
OR
awk '{gsub(/^[^|]*\||_[0-9]$/,"");gsub(/_[0-9]\|/,",")} 1' Input_file
输出如下。
line1,line2,line3
说明: 现在添加上述代码的说明。
awk -F'|' ' ##Setting field separator as | here for all lines.
{ ##Starting block here.
for(i=2;i<=NF;i++){ ##Starting for loop starting form i=2 to till value of NF here.
sub(/_.*/,"",$i) ##Using sub for substitution from _ to till everything with NULL in value of $i.
val=val?val OFS $i:$i ##Creating variable val and concatenate its own value if it is having NON ZERO value else save in it for 1st time.
} ##Close for loop block here.
print val ##Printing value of val here.
val="" ##Nullifying value of variable val here.
}' OFS="," Input_file ##Setting value of OFS to comma here and mentioning Input_file name here.