2016-05-13 43 views
0

你好我想在終端中用awk在我的CSV文件中添加列標題。在終端中用AWK添加CSV格式的列標題

當前顯示:

Michael, [email protected], Seattle, Washington, detail1, detail2, detail3 

所需的格式:

Name, Email, City, State, more1, more2, more3etc 
Michael, [email protected], Seattle, Washington, detail1, detail2, detail3, 

是否嘗試過這樣的事情,但我最終得到 「非法口供的源代碼行2」:

awk 'BEGIN {FS=",";OFS=","; print "Rating,Restaurant,Address,Landline,Mobile,Cuisine,Website,LatDD,LonDD"} 
NR >1 {print ",",,,",",",", }' Restaurants.txt > Restaurants_newer.txt 
+2

這一問題是否會減少對 「插入我的文件的開頭行」? –

+1

爲什麼所需格式的第一行與您試圖插入awk命令的格式不同? –

+1

第二次打印有語法錯誤:太多','。 –

回答

2

這會做

sed '1iName, Email, City, State, more1, more2, more3etc' file > newfile 

可以在適當位置做得太

sed -i '1iName, Email, City, State, more1, more2, more3etc' file 

{ echo 'Name, Email, City, State, more1, more2, more3etc'; cat file; } > newfile 
+0

感謝您的幫助,但是...我在終端上得到了這個: >命令我期望\然後是文本 – Michael

+0

哪個命令?另外,你的操作系統是什麼? – karakfa

+0

不確定,和OSX。 – Michael

0

使用AWK:

awk 'BEGIN{print "Name, Email, City, State, more1, more2, more3 .."}1' Restaurants.txt 

OR

試試這個:

echo "Name, Email, City, State, more1, more2, more3 .." >> Restaurants_newer.txt 
cat Restaurants.txt >> Restaurants_newer.txt 

即將文件輸出的標題行&重定向到文件中。

OR

{ printf 'Name, Email, City, State, more1, more2, more3 ..'; cat Restaurants.txt; } > Restaurants_newer.txt 
+0

感謝您的幫助,但是...我在終端上得到了這個: >命令我期望\接着是文本 – Michael

+0

@Michael檢查編輯答案。 –

2
awk ' 
BEGIN { OFS=", "; print "Name", "Email", "City", "State", "more1", "more2", "more3etc" } 
{ print $0, "" } 
' file 
+0

嗯,這是行不通的。我試過這個後,我的CSV文件仍然顯示爲空白。 雖然謝謝。 – Michael

+0

腳本不能做你聲稱它正在做的事情。當你說「我的CSV文件...」idk如果你的意思是你的輸入文件或你的輸出文件,但該腳本不能清空你的輸入文件,因爲它不寫入它,它不能產生一個空的輸出文件,因爲BEGIN節無論如何都會打印一行。你做錯了,所以編輯你的問題來複制/粘貼你正在運行的命令行和它產生的輸出,這樣我們就可以看到你在做什麼來幫助你調試它。 –