2014-07-22 330 views
5

我有一個問題,我似乎無法自己修復,也沒有通過搜索互聯網。轉換列表爲雙引號逗號分隔字符串

我有一個列表,保存在一個文件中,就像這樣:

apple 
banana 
pineapple 

而且我想每個字符串是在雙引號和逗號分隔,例如:

"apple","banana","pineapple" 

理想情況下,該列表的最後一個字不應該有逗號,但這不是強制性的。

這個想法背後的想法是能夠創建一個JSON格式的文件,由存儲在純文本文件中的項目列表填充。

非常感謝。

回答

5
awk -v RS='' -v OFS='","' 'NF { $1 = $1; print "\"" $0 "\"" }' file 

輸出:

"apple","banana","pineapple" 
+0

大非常感謝!我在這裏嘗試了類似於另一個線程的東西,但無法使其工作。您的解決方案完美運作。 – Nesousx

+0

@Nesousx我加了一個小小的調整來確保周圍有確實的字段。不客氣:) – konsolebox

+1

'$ 1 = $ 1'做什麼? –

0

另一個awk

awk '{printf "\"%s\"",$1}' file | awk '{gsub(/""/,"\",\"")}1' 
"apple","banana","pineapple" 

awk '{printf "\"%s\"",$1}' file | sed 's/""/","/g' 
2

我覺得是Perl也值得一提:

perl -lne 'push @a, qq("$_") }{ print join(",", @a)' file 

構建一個數組@a,其中包含每行的值,用雙引號括起來。然後,文件處理完畢後,打印出一個以逗號分隔的@a中所有元素的列表。

所謂eskimo greeting }{是用於創建END塊,由於該-n-p開關被實施的方式的簡寫。

輸出:

"apple","banana","pineapple" 

如果這是你要找的JSON,你可以使用encode_json

perl -MJSON -lne 'push @a, $_ }{ print encode_json(\@a)' file 

這會把數組轉換成一個真正的JSON編碼的列表:

["apple","banana","pineapple"] 
+0

'} {'是一個有趣的技巧,但是應該爲新手讀者的利益澄清,它只是'-p'的一個副作用,用'{}'包裝表達式,而不是某種關鍵字,本身 –

+1

@Josip我編輯添加一點點關於。 –

0

沒有花哨的東西awk:

awk 'x{x=x","}{x=x"\""$1"\""}END{print x}' file 

解釋版本:

awk ' 
    out { out = out "," }   # if there is already something in the output string, append a comma to it 
     { out = out "\"" $1 "\"" } # always append the quoted first column of input to the output string 
    END { print out }    # finally, print the output string 
' file 

的前兩行的事項的特有順序 - 它防止最終逗號被追加。

1

您也可以使用這個方法:

sed -r ':loop ; N ; s/\n/,/g ; $s/[^,]+/"&"/g ; t loop' filename 
0

sedpaste解決方案:

sed -e 's/^\|$/"/g' file | paste -s -d, - 
相關問題