仅使用 awk,如何将以下文本转换为:
$ cat latest.csv
psga,alp1acscf0001vm001oam001p1n004v001,192.7.129.7,UVP
apsga,alp1acscf0001vm001oam001p1n004v002,192.7.129.8,UVP
apsga,alp1acscf0001vm002oam001p1n004v001,192.7.129.9,UVP
apsga,alp1acscf0001vm003oam001p1n004v001,192.7.129.10,UVP
apsga,alp1acscf0001vm004cif001p1n004v001,192.7.129.11,UVP
apsga,alp1acscf0001vm004cif001p1n004v002,192.7.129.12,UVP
apsga,alp1acscf0001vm005cif001p1n004v001,192.7.129.13,UVP
我设法得到以下输出:
$ awk -F',' '{ print substr($2, 1, 14), (substr($2, 1, 18)),$3 }' latest.csv
alp1acscf0001v alp1acscf0001vm001 192.7.129.7
alp1acscf0001v alp1acscf0001vm001 192.7.129.8
alp1acscf0001v alp1acscf0001vm002 192.7.129.9
alp1acscf0001v alp1acscf0001vm003 192.7.129.10
alp1acscf0001v alp1acscf0001vm004 192.7.129.11
alp1acscf0001v alp1acscf0001vm004 192.7.129.12
alp1acscf0001v alp1acscf0001vm005 192.7.129.13
不过我想要第一个substr($2, 1, 14)
仅在行首一次其余的在一行中如下:
alp1acscf0001v alp1acscf0001vm001 192.7.129.7 alp1acscf0001vm001 192.7.129.8 alp1acscf0001vm002 192.7.129.9 alp1acscf0001vm003 192.7.129.10 alp1acscf0001vm004 192.7.129.11 alp1acscf0001vm004 192.7.129.12 alp1acscf0001vm005 192.7.129.13
答案1
awk -F, '
{ printf "%s %s %s", (NR==1 ? substr($2, 1, 14) : ""), substr($2, 1, 18), $3 }
END{ print "" }
' latest.csv
这仅打印第一个输入记录的第一个子字符串。$3
为所有记录打印另一个子字符串 plus 。在END
块中,打印换行符。
答案2
命令:
awk -F "," 'BEGIN{print "alp1acscf0001v"}ORS=" "{print substr($2,1,18),$3}' filename |perl -pne "s/\n/ /g"
输出
alp1acscf0001v alp1acscf0001vm001 192.7.129.7 alp1acscf0001vm001 192.7.129.8 alp1acscf0001vm002 192.7.129.9 alp1acscf0001vm003 192.7.129.10 alp1acscf0001vm004 192.7.129.11 alp1acscf0001vm004 192.7.129.12 alp1acscf0001vm005 192.7.129.13