2013-10-09 203 views
0

我有一個.CSV文件(可以說名爲file.csv)帶有數字和字符串值。該字符串可能包含逗號,因此它們用雙引號括起來,如下面的格式所示。在CSV文件末尾添加空列

column1,column2,column3,column4,column5,column6,column7 
12,455,"string, with, quotes, and with, commas, in between",4432,6787,890,88 
4432,6787,"another, string, with, quotes, and, with, multiple, commaz, in between",890,88,12,455 
11,22,"simple, string",77,777,333,22 

當我試圖在文件的末尾添加空列,使用下面的代碼

awk -F, '{NF=13}1' OFS="," file.csv > temp_file.csv 

輸出不按我的要求。該代碼還計算文本限定符字段中的逗號,並用雙引號括起來。使用上述命令中的文件cat temp_file.csv的輸出是如下:

column1,column2,column3,column4,column5,column6,column7,,,,,, 
12,455,"string, with, quotes, and with, commas, in between",4432,6787,890,88, 
4432,6787,"another, string, with, quotes, and, with, multiple, commaz, in between",890,88 
11,22,"simple, string",77,777,333,22,,,,, 

在哪裏,因爲我需要在該領域字段的總數使用爲13.在這個問題上的任何輸入要麼awksed非常感謝。

+0

您是否擁有對CSV生成的控制權?如果是這樣,你可以使用不同的字段分隔符(比如|)嗎? – SheetJS

+0

文件末尾有很多空格。 – Jotne

+0

@Nirk我不生成CSV。我從其中一位顧客那裏得到它。 – Dhruuv

回答

0
awk -F, '{sub(/ *$/,"");$0=$0 ","}1' OFS=, 
column1,column2,column3,column4,column5,column6,column7, 
12,455,"string, with, quotes, and with, commas, in between",4432,6787,890,88, 
4432,6787,"another, string, with, quotes, and, with, multiple, commaz, in between",890,88,12,455, 
11,22,"simple, string",77,777,333,22, 

這將刪除尾隨空格並在末尾添加一個字段。

-1

如果輸入總是有7場張貼那麼你挑:

awk '{print $0 ",,,,,,"}' file 
sed 's/$/,,,,,,/' file 

或刪除尾隨空格:

awk '{sub(/ *$/,",,,,,,")}1' file 
sed 's/ *$/,,,,,,/' file 

如果你的輸入文件可以有本領域的不同的數字,但仍顯示標題行:

awk -F, 'NR==1{flds=sprintf("%*s",13-NF,""); gsub(/ /,FS,flds)} {sub(/ *$/,flds)} 1' file 
column1,column2,column3,column4,column5,column6,column7,,,,,, 
12,455,"string, with, quotes, and with, commas, in between",4432,6787,890,88,,,,,, 
4432,6787,"another, string, with, quotes, and, with, multiple, commaz, in between",890,88,12,455,,,,,, 
11,22,"simple, string",77,777,333,22,,,,,,