Linux sed命令 - 使用带反斜杠的变量

问题描述:

我试图替换文件中的字符串。我必须使用一个变量,因为我必须在很多行中执行此操作。我如何逃避反斜杠?Linux sed命令 - 使用带反斜杠的变量

的text.txt:

1234567#Hello World#Hello I\u0027m Scott 

脚本:

#!/bin/bash 
FOLDERID=`cat text.txt | cut -d# -f1` # example: 12345 
oldstring=`cat text.txt | cut -d# -f2` # example: "Hello World" 
newstring=`cat text.txt | cut -d# -f3` # example: "Hello I\u0027m Scott" 
sed -i "s/${oldstring}/${newstring}/g" $FOLDERID/myfile.txt 

猫myfile.txt的sed的后

Hello I0027m Scott 

我怎能逃脱反斜线?我只知道如何逃生斜线这将工作,如:

newstring=Hello I/u0027m Scott 
newstring=${newstring//\//\\\/} 
echo ${newstring} # => Hello I\/u0027m Scott 
+0

你可以添加一个更清晰的例子吗?最好按以下顺序:1)修改前的myfile.txt的内容2)外部文件的内容3)包含要替换的字符串的变量4)更改后的'myfile.txt'的期望输出 – Sundeep

+0

myfile.txt包含文本+旧字符串 – professorswag123

+0

只是为了澄清,'\ u0027'是六个字符'''''''''''''0''0''2''7,或者它是Unicode字符,十六进制值为0x27 '(即''')?我假设前者,但想检查以防万一。 **另外**,请参阅[此问题](https://*.com/q/29613304/2877364)。 – cxw

试试这个:

cd /tmp 
mkdir -p 1234567 
echo Hello World >1234567/myfile.txt 
echo '1234567#Hello World#Hello I\u0027m Scott' >text.txt 

好吧,那么:

IFS=\# read -r FOLDERID oldstring newstring <text.txt 
sed "s/${oldstring}/${newstring//\\/\\\\}/g" -i $FOLDERID/myfile.txt 
cat 1234567/myfile.txt 
Hello I\u0027m Scott