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