awk命令拆分第n个字段 [英] awk command to split nth field
本文介绍了awk命令拆分第n个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在学习AWK,并且正在尝试一些有关内置字符串函数的练习.
I am learning AWK and was trying some exercises on built-in string functions.
这是我的锻炼:
我有一个包含以下内容的文件
I have a file containing as below
RecordType:83
1,2,3,a|x|y|z,4,5
我想要的输出如下:
RecordType:83
1,2,3,a,4,5
1,0,0,x,4,5
1,0,0,y,4,5
1,0,0,z,4,5
我为上面的输出写了一个awk命令.
I wrote an awk command for the above output.
awk -F',' '$1 ~ /RecordType:83/{print $0}
$1 == 1{
split($4,splt,"|")
for(i in splt)
{
if(i==1)
print $1,$2,$3,splt[i],$5,$6
else
print $1,0,0,splt[i],$5,$6
}
}' OFS=, file_name
上面的命令看起来很笨拙.有什么办法可以最小化命令?
The above command looks so clumsy. Is there any way minimizing the command?
预先感谢
推荐答案
我能管理的最短的一线飞机:
The shortest possible one-liner I could manage:
awk -F, 'NR>1{n=split($4,a,"|");for(;i++<n;){$4=a[i];print;$2=$3=0}}NR==1' OFS=, file
RecordType:83
1,2,3,a,4,5
1,0,0,x,4,5
1,0,0,y,4,5
1,0,0,z,4,5
更具可读性的脚本(推荐):
BEGIN {
FS=OFS="," # Comma delimiter
}
NR==1 { # If the first line in file
print $0 # Print the whole line
next # Skip to next line
}
{
n=split($4,a,"|") # Split field four on |
for(i=1;i<=n;i++) # For each sub-field
print $1,i==1?$2OFS$3:"0"OFS"0",a[i],$5,$6 # Print the output
}
这篇关于awk命令拆分第n个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文