我的文件中有\n
字符串。在bash腳本中替換字符串' n'(不是'行尾')
文件source.txt
的內容只有一個文本行(加在第一行的末尾輸入):
I want to replace only substring \nconsisting of characters \\ and n
你可以看到\n
子裏面之前「由」字。我想用子字符串\n
和一些ident空格替換這個子字符串。我的腳本文件script.sh
:呼叫script.sh
從慶典後
#!/bin/bash
ident=" "
rep_old="\n"
rep_new="\n$ident"
FILE=source.txt
while read line
do
echo -e "$line"
echo -e "NEW: ${line//$rep_old/$rep_new}"
done < $FILE
實際輸出(我的操作系統是Windows):
I want to replace only substring nconsisting of characters \ and n
NEW: I wa
t to replace o
ly substri
g
co
sisti
g of characters \ a
d
但我想只更換一個\n
。我也嘗試使用rep_old="\\n"
但沒有成功。實現這兩種結果變體的正確方法是什麼?
1:I want to replace only substring \n consisting of characters \\ and n
2:I want to replace only substring consisting of characters \\ and n
我做的嘗試爲基礎,以你的答案:
答:rep_old="\\\\n"
答:結果:
I want to replace only substring nconsisting of characters \ and n
NEW: I want to replace only substring nconsisting of characters \ and n
對不起,這不幫我。看到我的更新問題與此測試 - 沒有身份證,看起來像什麼都沒有被取代。 – Atiris 2014-09-26 09:04:52
謝謝,這是雙重逃脫的正確解決方案。 – Atiris 2014-09-26 09:19:45