2015-05-04 37 views
3

我有一個字符串,我需要使用shell腳本將「,」替換爲「\」。我以爲我可以使用sed來做到這一點,但沒有運氣。如何在使用sed的字符串中將逗號替換爲「」

+0

Stack Overflow是用於編程和發展問題的站點。這個問題似乎與題目無關,因爲它不涉及編程或開發。請參閱幫助中心的[我可以詢問哪些主題](http://stackoverflow.com/help/on-topic)。也許[超級用戶](http://superuser.com/)或[Unix&Linux堆棧交換](http://unix.stackexchange.com/)會是一個更好的地方。 – jww

回答

2

你可以做,沒有sed

string="${string/,/\\,}" 

要更換所有的 「」 使用這樣的:

string="${string//,/\\,}" 

例子:

#!/bin/bash 
string="Hello,World" 
string="${string/,/\\,}" 
echo "$string" 

輸出:

Hello\,World 
2

你需要逃避反斜槓\/
我不知道你的輸入是什麼,但這種將工作:

echo "teste,test" |sed 's/,/\\/g' 

輸出:

teste\test 

演示: http://ideone.com/JUTp1X


如果字符串上的一個文件,你可以使用:

sed -i 's/,/\//g' myfile.txt 
+0

不錯,但請注意,OP希望用'\,'替換',',而不僅僅是'\'。 – mklement0

相關問題