2014-09-26 51 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