-1
如何用bash替換"
的\"
字符串?用字符串替換「by 」
例如:
一個txt文件包含的文本,如:
Banana "hallo" Apple "hey"
這必須被轉換成:
Banana \"hallo\" Apple \"hey\"
我試圖
a=$(cat test.txt)
b=${a//\"/\"}}
但這並沒有我RK。
這是如何工作的?
如何用bash替換"
的\"
字符串?用字符串替換「by 」
例如:
一個txt文件包含的文本,如:
Banana "hallo" Apple "hey"
這必須被轉換成:
Banana \"hallo\" Apple \"hey\"
我試圖
a=$(cat test.txt)
b=${a//\"/\"}}
但這並沒有我RK。
這是如何工作的?
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}
替換var
與replacement
的pattern
一個發生。
${var//pattern/replacement}
取代在var
所有出現pattern
與replacement
。
如果模式或替換包含字符如"
或/
在shell中有特殊含義,則需要將它們轉義以讓shell將它們視爲文字。
你能告訴我們你到目前爲止嘗試過什麼嗎? – m0skit0
例如a = $(cat test.txt)和b = $ {a // \「/ \」}}這當然不起作用 –
您的問題對您的要求有點模糊。一般來說,你可以用'sed'或者''awk'來解決這個問題。還有其他的可能性。 –