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

时间:2016-10-27 12:38:12

标签: linux bash shell sed scripting

我正在尝试替换文件中的字符串。我必须使用变量,因为我必须在很多行中执行此操作。我如何逃避反斜杠?

的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
sed之后

cat myfile.txt

Hello I0027m Scott

我怎么能逃避反斜杠?我只知道如何逃避斜线,如:

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

2 个答案:

答案 0 :(得分:2)

试试这个:

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

答案 1 :(得分:0)

@ F.Hauri的示例对我有用,但就我而言,左边的字符串可能带有反斜杠,所以我这样做了:

#!/bin/bash

source my.cfg -r # Read VAR from my.cfg

echo "Old variable is \"${VAR}\""
echo -n "Input   : "
read -r newvar
echo    "You said: \"${newvar}\""

sed -i -e "s/'${VAR//\\/\\\\}'/'${newvar//\\/\\\\}'/g" my.cfg

echo "my.cfg is now:"
echo
cat my.cfg

但是我要承认,我并不完全理解

//\\/\\\\