2016-12-15 134 views
-1

如何用bash替換"\"字符串?用字符串替換「by 」

例如:

一個txt文件包含的文本,如:

Banana "hallo" Apple "hey" 

這必須被轉換成:

Banana \"hallo\" Apple \"hey\" 

我試圖

a=$(cat test.txt) 
b=${a//\"/\"}} 

但這並沒有我RK。

這是如何工作的?

+0

你能告訴我們你到目前爲止嘗試過什麼嗎? – m0skit0

+0

例如a = $(cat test.txt)和b = $ {a // \「/ \」}}這當然不起作用 –

+0

您的問題對您的要求有點模糊。一般來說,你可以用'sed'或者''awk'來解決這個問題。還有其他的可能性。 –

回答

1

使用[ parameter expansion ]

string='Banana "hallo" Apple "hey"' 
echo "$string" 
Banana "hallo" Apple "hey" 
string=${string//\"/\\\"} # Note both '\' need '"' need to be escaped. 
echo "$string" 
Banana \"hallo\" Apple \"hey\" 

阿律解釋

${var/pattern/replacement} 

替換varreplacementpattern一個發生。

${var//pattern/replacement} 

取代var所有出現patternreplacement

如果模式或替換包含字符如"/在shell中有特殊含義,則需要將它們轉義以讓shell將它們視爲文字。