【问题标题】:why sed command can work directly and can't work when I write it in script file?为什么 sed 命令可以直接工作,而我在脚本文件中编写时不能工作?
【发布时间】:2012-12-08 19:06:39
【问题描述】:

这是我的上下文: 我有一个名为 profile 的个人资料

# file: profile

MY_PATH = "/home/deng/default"
MY_NAME = "deng" 

我的测试文件:

#!/bin/sh
#file: test.sh
DJ_PATH="/deng/jian/doc"

OUTPUT_PATH="\"${DJ_PATH}/output\""
echo "OUTPUT_PATH = ${OUTPUT_PATH}"

DOC_KEY="MY_PATH"
DOC_VALUE=${OUTPUT_PATH}
echo "DOC_VALUE = ${DOC_VALUE}"

echo "sed 's:[ \t]*${DOC_KEY}[ \t]*=.*:${DOC_KEY} = ${DOC_VALUE}:' profile"
sed 's:[ \t]*${DOC_KEY}[ \t]*=.*:${DOC_KEY} = ${DOC_VALUE}:' profile

在终端我运行

$ ./test.sh 

输出是

1  OUTPUT_PATH = "/deng/jian/doc/output"
2  DOC_VALUE = "/deng/jian/doc/output"
3  sed 's:[ \t]*MY_PATH[ \t]*=.*:MY_PATH = "/deng/jian/doc/output":' profile
4   MY_PATH = "/home/deng/default"
5   MY_NAME = "deng"

看起来配置文件中的文本没有被我想要设置的 DOC_VALUE ("/deng/jian/doc/output") 替换。但我在输出第 3 行运行了命令。它有效:

sed 's:[ \t]*MY_PATH[ \t]*=.*:MY_PATH = "/deng/jian/doc/output":' profile

输出:

MY_PATH = "/deng/jian/doc/output"
MY_NAME = "deng"

那么发生了什么?我在 test.sh 中写的命令有什么不同

sed 's:[ \t]*${DOC_KEY}[ \t]*=.*:${DOC_KEY} = ${DOC_VALUE}:' profile

还有我直接输入的命令?

sed 's:[ \t]*MY_PATH[ \t]*=.*:MY_PATH = "/deng/jian/doc/output":' profile

【问题讨论】:

    标签: bash shell sed command sh


    【解决方案1】:

    在你使用' 的文件中,它不会让 bash 解释变量。

    更改为"

    sed "s:[ \t]*${DOC_KEY}[ \t]*=.*:${DOC_KEY} = ${DOC_VALUE}:" profile
    

    或使用多个' 中断

    sed 's:[ \t]*'${DOC_KEY}'[ \t]*=.*:'${DOC_KEY}' = '${DOC_VALUE}':' profile
    

    【讨论】:

      【解决方案2】:

      看这个例子:

      #!/bin/sh
      
      S=foo
      D=bar
      
      echo 'foo' | sed 's/${S}/${D}/g'       # echoes foo
      echo 'foo' | sed 's/'${S}'/'${D}'/g'   # echoes bar
      

      【讨论】:

        猜你喜欢
        • 2020-04-27
        • 2014-10-06
        • 1970-01-01
        • 2012-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-25
        相关资源
        最近更新 更多