我正在尝试替换文件中的字符串。我必须使用一个变量因为我必须在很多行中做这个。如何转义反斜杠?
text.txt:
1234567#Hello World#Hello Iu0027m 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 Iu0027m Scott"
sed -i "s/${oldstring}/${newstring}/g" $FOLDERID/myfile.txt
cat myfile.txt after sed
Hello I0027m Scott
如何转义反斜杠?我只知道如何转义斜杠,它的工作方式是:
newstring=Hello I/u0027m Scott
newstring=${newstring////\/}
echo ${newstring} # => Hello I/u0027m Scott
试试这个:
cd /tmp
mkdir -p 1234567
echo Hello World >1234567/myfile.txt
echo '1234567#Hello World#Hello Iu0027m 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 Iu0027m Scott
@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
但我要承认,我不完全理解
//\/\\