在扫描并重新处理输入csv文件后,我希望能够基本上沿着输出中的每一行打印行号。输入的csv文件是逗号分隔的,这里有一个示例
Timestamp,Email,Name,Year,Make,Model,Car_ID,Judge_ID,Judge_Name,Racer_Turbo,Racer_Supercharged,Racer_Performance,Racer_Horsepower,Car_Overall,Engine_Modifications,Engine_Performance,Engine_Chrome,Engine_Detailing,Engine_Cleanliness,Body_Frame_Undercarriage,Body_Frame_Suspension,Body_Frame_Chrome,Body_Frame_Detailing,Body_Frame_Cleanliness,Mods_Paint,Mods_Body,Mods_Wrap,Mods_Rims,Mods_Interior,Mods_Other,Mods_ICE,Mods_Aftermarket,Mods_WIP,Mods_Overall
8/5/2018 14:10,honoland13@japanpost.jp,Hernando,2015,Acura,TLX,48,J04,Bob,0,0,2,2,4,4,0,2,4,4,2,4,2,2,2,2,2,0,4,4,4,6,2,0,4
8/5/2018 15:11,nlighterness2q@umn.edu,Noel,2015,Jeep,Wrangler,124,J02,Carl,0,6,4,2,4,6,6,4,4,4,6,6,6,6,6,4,6,6,6,6,6,4,6,4,6
8/5/2018 17:10,eguest47@microsoft.com,Edan,2015,Lexus,Is250,222,J05,Adrian,0,0,0,0,0,0,0,0,6,6,6,0,0,6,6,6,0,0,0,0,0,0,0,0,4
8/5/2018 17:34,hchilley40@fema.gov,Hieronymus,1993,Honda,Civic eG,207,J06,Aaron,0,0,2,2,2,2,2,2,0,4,2,2,2,2,2,2,4,2,2,0,0,0,2,2,0
8/5/2018 14:30,nnowick3d@tuttocitta.it,Nickolas,2016,Ford,Mystang,167,J02,Carl,0,0,2,2,0,2,2,0,0,0,0,2,0,2,2,2,0,0,2,0,0,0,0,0,2
8/5/2018 16:12,mdearl39@amazon.co.uk,Martin,2013,Hyundai,Gen coupe,159,J04,Bob,0,0,2,0,0,0,2,0,0,0,0,2,0,2,2,0,2,0,2,0,0,0,0,0,0
8/5/2018 17:00,alynamg@blogtalkradio.com,Aldridge,2009,Infiniti,G37,20,J06,Aaron,2,0,2,2,0,0,2,0,0,2,2,2,2,2,2,2,2,2,4,2,2,0,2,0,2
我的代码目前所做的是筛选csv文件,并选择car_id列、year列、make列和model列。然后,它遍历从racer_turbo到最后一列的每一列,对于每一行,它将这些列中的值相加为一个总值,并将其与其他值(id、make、model等(一起打印。打印时,还有一个排名列在其他5列之前。下面是我的代码。
BEGIN {
FS = ",";
OFS = "t";
print "Ranking", "Car_ID", "Year", "Make", "Model", "Total";
}
FNR > 1 {
rank = 0;
total = 0;
if(NR > 1) {
for(i = 8; i < NF; i++) {
total += $i;
}
print ++rank,$7,$4,$5,$6,total;
}
}
END {
}
我的当前输出如下
Ranking Car_ID Year Make Model Total
1 48 2015 Acura TLX 58
1 124 2015 Jeep Wrangler 118
1 222 2015 Lexus Is250 36
1 207 1993 Honda Civic eG 40
1 167 2016 Ford Mystang 18
1 159 2013 Hyundai Gen coupe 14
1 20 2009 Infiniti G37 36
1 178 2009 Honda Oddesy 66
我的问题是,在排名列下,它每行只显示1,我需要它能够从1开始递增,然后递减文档中的行数。现在,在我的代码中很明显,我有一个秩变量,它充当了一个跟踪器,我想随着打印的每一行而递增,但它只为每一行打印1。我该怎么解决?
预期输出是这个
Ranking Car_ID Year Make Model Total
1 48 2015 Acura TLX 58
2 124 2015 Jeep Wrangler 118
3 222 2015 Lexus Is250 36
4 207 1993 Honda Civic eG 40
5 167 2016 Ford Mystang 18
6 159 2013 Hyundai Gen coupe 14
7 20 2009 Infiniti G37 36
8 178 2009 Honda Oddesy 66
请注意,我的机器正在运行AWK的4.0.2版本。
在这种情况下,您不需要自己的变量,只需从NR
中减去1
即可获得所需的输出,即
BEGIN {
FS = ",";
OFS = "t";
print "Ranking", "Car_ID", "Year", "Make", "Model", "Total";
}
FNR > 1 {
total = 0;
if(NR > 1) {
for(i = 8; i < NF; i++) {
total += $i;
}
print NR-1,$7,$4,$5,$6,total;
}
}
附带说明:END
是可选的,您不必在GNUAWK
命令中有一个。