【问题标题】:shell script, how to escape variables?shell脚本,如何转义变量?
【发布时间】:2015-07-08 07:23:05
【问题描述】:

我正在编写一个 shell 脚本,我在其中输入了一个值并希望将该值用于其他一些命令。我的问题是我想转义这个值。

例如,如果我在下面的脚本中输入http://example.com

echo "Input a value for my_value"
read my_value

echo $my_value

这将导致http://example.com

但我希望的结果是http\:\/\/example\.com

我如何做到这一点?


我要运行的命令是

sed -i s/url/$my_value/g somefile.html

没有转义,它变成sed -i s/url/http://example.com/g somefile.html,这显然是一个语法错误..

【问题讨论】:

  • my_value=${my_value//\/\//\\/\\/}

标签: shell sed escaping


【解决方案1】:

您可以使用其他字符来拆分s 参数。我喜欢,

sed -i 's,url,http://example.com,g'

。如果你真的想要它,你可以在执行之前使用 sed 替换参数中的/

url=$(echo "http://example.com"|sed 's,/,\\/,g')
sed -i 's/url/'"$url"'/g' input

【讨论】:

    【解决方案2】:

    变量中的/无需转义,您可以在sed中使用备用正则表达式分隔符:

    sed -i "s~url~$my_value~g" somefile.html
    

    【讨论】:

      【解决方案3】:

      在任何非字母数字字符前添加斜线:

      $ my_value=http://example.com
      $ my_value=$(sed 's/[^[:alnum:]]/\\&/g' <<<"$my_value")
      $ echo "$my_value"
      http\:\/\/example\.com
      

      但是,如果您想在 sed 命令中使用它,则需要将反斜杠加倍

      $ echo this is the url here | sed "s#url#$my_value#g"
      this is the http://example.com here
      $ echo this is the url here | sed "s#url#${my_value//\\/\\\\}#g"
      this is the http\:\/\/example\.com here
      

      【讨论】:

        【解决方案4】:

        您遇到的问题是您只想用不同的文字字符串替换一个文字字符串,但 sed 不能对字符串进行操作。有关 sed 解决方法,请参阅Is it possible to escape regex metacharacters reliably with sed,但您最好只使用可以处理字符串的工具,例如awk:

        awk -v old='original string' -v new='replacement string' '
            s=index($0,old) { $0 = substr($0,1,s-1) new substr($0,s+length(old)) }
            { print }
        ' file
        

        【讨论】:

          猜你喜欢
          • 2018-04-11
          • 2021-05-24
          • 1970-01-01
          • 2010-12-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-15
          相关资源
          最近更新 更多