我必须从文件'main.csv'中读取并打印输出如下:
Set 4,1095,Set 1 or 4
Set 2,18277,Set 2 or 3
Set 1 or 4,Set 4,944
Set 2,1373,Set 2 or 3
Set 4,83,Set 1 or 4
Set 2,14356,Set 2 or 3
Set 2,14800,Set 2 or 3
我在下面尝试了各自的输出:
awk 'BEGIN {FS=","}{OFS=","}{print $12,$15}' main.csv
Set 4,1095
Set 2,18277
Set 4,944
Set 2,1373
Set 4,83
awk 'BEGIN {FS=","}{OFS=","}{if($12 == "Set 1" || $12 == "Set 4"){print "Set 1 or 4",$12,$15}else{print "Set 2 or 3",$12,$15}}' main.csv
Set 1 or 4,Set 4,1095
Set 2 or 3,Set 2,18277
Set 1 or 4,Set 4,944
Set 2 or 3,Set 2,1373
Set 1 or 4,Set 4,83
Set 2 or 3,Set 2,14356
Set 2 or 3,Set 2,14800
awk 'BEGIN {FS=","}{OFS=","}{if($12 == "Set 1" || $12 == "Set 4"){print $12,$15,"Set 1 or 4"}else{print $12,$15,"Set 2 or 3"}}' main.csv
,Set 1 or 4
,Set 2 or 3
,Set 1 or 4
,Set 2 or 3
,Set 1 or 4
,Set 2 or 3
,Set 2 or 3
前 2 个“awk”运行良好,那么为什么不是第三个呢?
main.csv 每行有 15 个逗号分隔值,第 12 个值如下所示:
Set 1
Set 2
Set 3
Set 4
PS:我在 Solaris 10 上使用 bash
我仍然对“awk”问题很感兴趣,以下是我注意到的……不知道为什么会发生(我在 Solaris 10 和 RHEL 5 上都遇到了这个问题)
awk -F, '{print "Var13->"$13,"\t","Var12->"$12,"\t","Var15 ->"$15}' < main.csv
Var13->0 Var12->Set 4 Var15 ->1095
Var13->1631 Var12->Set 2 Var15 ->18277
Var13->0 Var12->Set 4 Var15 ->944
Var13->2832 Var12->Set 2 Var15 ->1373
Var13->0 Var12->Set 4 Var15 ->83
awk -F, '{print "Var13 & Var15->"$13,"\t","Var12->"$12,"\t","Var15 ->"$15}' < main.csv
Var13 & Var15->0 Var12->Set 4 Var15 ->1095
Var13 & Var15->1631 Var12->Set 2 Var15 ->18277
Var13 & Var15->0 Var12->Set 4 Var15 ->944
Var13 & Var15->2832 Var12->Set 2 Var15 ->1373
Var13 & Var15->0 Var12->Set 4 Var15 ->83
awk -F, '{print "Var13 & Var15->"$13,$15"\t","Var12->"$12,"\t","Var15 ->"$15}' < main.csv
or
awk -F, '{print "Var13 & Var15->"$13,$15,"\t","Var12->"$12,"\t","Var15 ->"$15}' < main.csv
or
awk -F, '{print "Var13 & Var15->"$13,"\t",$15,"\t","Var12->"$12,"\t","Var15 ->"$15}' < main.csv
ar13 & Var12->Set 4 Var15 ->1095
ar13 & Var12->Set 2 27 Var15 ->18277
ar13 & Var12->Set 4 Var15 ->944
ar13 & Var12->Set 2 73 Var15 ->1373
ar13 & Var12->Set 4 Var15 ->83
ar13 & Var12->Set 2 56 Var15 ->14356
正如你所看到的,最后 3 次运行已经吃掉了“Var13”输出中的字母并添加了一些垃圾信息。