【发布时间】:2017-03-10 03:33:11
【问题描述】:
我正在尝试替换文件中的字符串。我必须使用一个变量,因为我必须在很多行中这样做。我如何逃避反斜杠?
文本.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
【问题讨论】:
-
你能添加一个更清晰的例子吗?最好按以下顺序:1)修改前
myfile.txt的内容2)external file的内容3)包含要替换的字符串的变量4)修改后myfile.txt的预期输出 -
myfile.txt 包含文本 + 旧字符串
-
澄清一下,
\u0027是六个字符\u0027,还是十六进制值@987654336的Unicode字符@(即')?我假设是前者,但想检查一下以防万一。 另外,见this question。 -
是的,它是 unicode ' 但我必须这样写
-
text.txt 中的六个字节
标签: linux bash shell sed scripting