【问题标题】:Linux sed command - using variable with backslashLinux sed 命令 - 使用带反斜杠的变量
【发布时间】: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


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    @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
    

    但我承认,我并不完全明白

    //\\/\\\\
    

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 1970-01-01
      • 1970-01-01
      • 2019-10-04
      • 2019-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-14
      相关资源
      最近更新 更多