替换字符串' \ n' (不是'行尾#39;)在bash脚本中

时间:2014-09-26 08:36:36

标签: windows string bash shell

我的文件中有\n个字符串。

文件source.txt的内容只有一行带有文字(加上第一行末尾的输入):

I want to replace only substring \nconsisting of characters \\ and n

你可以在“组成”单词之前看到\n个子串。我想用子串\n和一些ident空格替换这个子串。我的脚本位于文件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

从bash调用script.sh后的实际输出(我的操作系统是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 个答案:

答案 0 :(得分:1)

这与&#39;双重转义&#39;在变量设定时间和使用时发生 考虑一下:

$ echo "\\n"
\n

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

所以,即使我在上使用 创建,也可以在上使用转义n \ n

尝试:

$ rep_old="\\\\n"

给出了

$ 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