2016-12-29 79 views
1

我已經無休止地搜索了,找不到任何東西來解決看起來像是一個非常簡單的問題。awk在打印字段時切斷

我有以下行讀取csv文件,只是使用字段來創建一個新的字符串。

的輸入是一個簡單的2列組整數:

1234,1 
5678,2 
1357,5 
2468,4 

每個預期的輸出應該類似「的評級應該是1和id應該是1234」的每一行。

awk -F "," '{print "rating should be "$2" and id should be "$1}' $1 >> $FILENAME 

但這是輸出I得到:

and id should be 635277 
and id should be 29894 
and id should be 576076 

我認爲這是最簡單的字符串連接的情況下,但我完全陌生的awk的,所以我很可能會丟失一些明顯的事我怎樣才能得到這個打印我想要的字符串?

+0

@Inian當然,對不起。增加了額外的信息。 – ssb

回答

1

的問題無關,與你的awk腳本這是很好的原樣。您的輸入文件包含control-Ms,使用dos2unix或類似命令將其刪除。

+0

謝謝,我聽說行結束是一個問題。當我回到工作機器上時,我會驗證這一點,如果情況如此,請將接受的答案轉換爲此。 – ssb

2

推薦使用printf來打印帶引號的字符串,這是POSIX兼容並且跨平臺可用。

awk -F"," '{printf "rating should be %d and id should be %s\n", $2,$1}' input-file 
rating should be 1 and id should be 1234 
rating should be 2 and id should be 5678 
rating should be 5 and id should be 1357 
rating should be 4 and id should be 2468 

從你print例如修理你無端接雙引號字符串,解決了這個問題對我來說

awk -F "," '{print "rating should be "$2" and id should be "$1""}' input-file 
rating should be 1 and id should be 1234 
rating should be 2 and id should be 5678 
rating should be 5 and id should be 1357 
rating should be 4 and id should be 2468 
+0

工作過,謝謝,但是你知道我爲什麼用打印得到中斷輸出嗎? – ssb

+0

@ssb:那麼你有一個不平衡的雙引號開始! 'printf'是我的第一個想法,當涉及到打印自定義字符串時, – Inian

+0

@ssb:請參閱我的更新,瞭解如何修復它 – Inian