2014-09-26 119 views
0

我的文件中有\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 

回答

1

這是做「雙逃逸」,在變盤時間和使用時間 發生這樣考慮:

$ echo "\\n" 
\n 

$ x="\\n" 
$ echo $x 
\n 

所以即使我\\逃脫N於創作使用其\ n

嘗試:

$ rep_old="\\\\n" 

whic小時之後獲得

$ echo $rep_old 
\\n 

修訂 對不起你有第二個問題,那就是:

while read line <-- this is already eating the \n as it is reading that as an escape 
do 
    echo -e "$line" 

看到這一點: sh read command eats slashes in input?

試試這個:

while read -r line 

給予:

I want to replace only substring 
consisting of characters \ and n 
NEW: I want to replace only substring 
     consisting of characters \ and n 
+0

對不起,這不幫我。看到我的更新問題與此測試 - 沒有身份證,看起來像什麼都沒有被取代。 – Atiris 2014-09-26 09:04:52

+0

謝謝,這是雙重逃脫的正確解決方案。 – Atiris 2014-09-26 09:19:45