我在这样的文件中有一个值
"AERH1","505549_AdelaideCBDWest_3@505549_AdelaideCBDWest_3",BTS3900,16,16,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,
"AERH1","558018_ElizabethVale_3@558018_ElizabethVale_3_UL",BTS3900,448,336,6,1,1,90,0,1,1,1,1,1,0,6,0,6,6,6,6,0,6,0,0,0,0,0,6,6,0,0,0,6,6,0,6,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,15,0,0,0,0,0,0,1,0,0,0,0,0,0,6,0,6,0,6,0,0,0,0,0,0,0,0,0,0,0,0,
"AERH1","505138_Netley_3@505138_Netley_3",BTS3900,448,336,6,1,1,90,0,1,1,1,1,1,0,6,0,6,6,6,6,0,6,0,0,0,0,0,6,6,0,0,0,6,6,6,6,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,12,0,1,0,0,0,0,1,0,1,0,0,0,0,6,0,6,0,6,0,0,0,0,0,0,0,0,0,6,0,0,
"AERH1","558012_OneTreeHill_2@558012_OneTreeHill_2_UL",BTS3900,544,400,9,1,1,135,0,1,1,1,1,1,1,9,0,9,9,9,9,0,9,0,0,0,0,0,9,9,0,0,0,9,9,12,9,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,0,0,0,0,0,0,0,30,0,1,0,0,0,0,1,0,3,0,0,0,0,9,0,9,0,9,0,0,0,0,0,0,0,0,0,0,0,0,
我需要在每行中选择最多 6 个逗号,如下所示
"AERH1","505549_AdelaideCBDWest_3@505549_AdelaideCBDWest_3",BTS3900,16,16,1
答案1
使用cut
:
cut -d, -f 1-6 file
或者awk
:
awk -F, '{OFS=","; print $1,$2,$3,$4,$5,$6}' file
在这两种情况下,输出都是:
"AERH1","505549_AdelaideCBDWest_3@505549_AdelaideCBDWest_3",BTS3900,16,16,1
"AERH1","558018_ElizabethVale_3@558018_ElizabethVale_3_UL",BTS3900,448,336,6
"AERH1","505138_Netley_3@505138_Netley_3",BTS3900,448,336,6
"AERH1","558012_OneTreeHill_2@558012_OneTreeHill_2_UL",BTS3900,544,400,9
答案2
一种选择是使用 awk:
awk -F, '{ for(i=1;i<=5;i++) { printf "%s,",$i } printf "%s\n",$6 }' filename
浏览每个逗号分隔的字段最多五次,打印每个字段后跟一个逗号,最后打印第六部分。
答案3
CSV 有一些令人讨厌的边缘情况,因此最好使用 CSV 解析器。例如,对于 Ruby:
ruby -rcsv -e 'CSV.foreach(ARGV.shift) {|row| puts CSV.generate_line(row.first(6))}' file