【问题标题】:How to put bash variables in quotes如何将bash变量放在引号中
【发布时间】:2018-02-19 06:20:38
【问题描述】:
DMIDECODE=$cmd_.dmidecode
UNAME=$cmd_.uname
HOSTNAME=$cmd_.hostname

我想编写一个脚本,可以将这些变量放在目录或其子目录中存在的所有文件中的双引号中。例如:

DMIDECODE="$cmd_.dmidecode"
UNAME="$cmd_.uname"

我是一个初学者,但我已经尝试了各种方法来解决这个问题。我尝试为上述变量编写正则表达式,然后将变量值用双引号括起来。 我写的正则表达式是 ^(?!.[a-z])(?!.[0-9]).+[=][$].*$ 我要记住的是,变量应该以大写字母开头,然后是 = 和 $ 符号,然后是任何内容。

【问题讨论】:

    标签: linux bash


    【解决方案1】:

    你可以使用sed,像这样:

    sed 's/^\([[:upper:]][[:upper:]_]\{1,\}=\)\(.*\)[[:blank:]]*/\1"\2"/' file.sh
    

    解释:

    ^            # begin of the line
    \(           # start of capturing group 1
    [[:upper:]]  # uppercase character
    [[:upper:]]  # uppercase or underscore character
    \{1,\}       # one or more times
    =            # the literal =
    \)           # end of capturing group 1
    \(.*\)       # capturing group 2 contains the value
    [[:blank:]]* # optional white space at the end of the line
    

    【讨论】:

      【解决方案2】:

      另一个使用反向引用检查行尾的简单替代方法是:

      sed -i 's/[=]\([$].*$\)/="\1"/' filename
      

      使用-i 选项执行就地替换。在您的示例文件上调用上述内容的简短测试:

      DMIDECODE="$cmd_.dmidecode"
      UNAME="$cmd_.uname"
      HOSTNAME="$cmd_.hostname"
      

      【讨论】:

      • 这有点太不具体了。例如,这会将echo "$foo" 替换为echo ""$foo""
      • 是的,我喜欢你定制的方式,需要注意的是,这是基于示例文件的一种非常简单的方法,如果文件包含完整的脚本,则需要额外的保护,而不是只是变量/值文件用于作为配置源。我添加了[=] 以确保这是一项正在执行的任务,但所有这些警告仍然适用。
      猜你喜欢
      • 2012-06-28
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2020-02-14
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      • 2011-12-26
      相关资源
      最近更新 更多