【问题标题】:Sed not expanding * in variablesSed 没有在变量中扩展 *
【发布时间】:2021-02-17 23:16:58
【问题描述】:

我正在编写一个涉及带有通配符的路径的脚本。我知道通配符只会匹配一个文件,我只是提前不知道文件扩展名是什么,所以我使用了通配符。

这里的目标是找到相应文件的路径,然后将该路径添加到脚本的第 16 行。

我有这样的事情:

path=/path/to/somewhere/fileName*

sed "16 a file=$path" myScript.sh

我期望得到的是这个(第 16 行):

file=/path/to/somewhere/fileName.extension

但我得到的是:

file=/path/to/somewhere/fileName*

由于某种原因,sed 在添加 $path 的内容时没有扩展通配符,我不知道如何让 sed 做这样的事情。我正在寻找一种解决方案,a) sed 已正确扩展 $path 或 b) 在传递给 sed 之前让 $path 包含完全扩展的字符串。

【问题讨论】:

    标签: linux bash unix sed


    【解决方案1】:

    您的变量只包含一个字符串,然后您插入该字符串。 sed 不知道这不是你的意思。如果您希望 shell(不是 sed!)扩展通配符,可能使用循环。

    for path in /path/to/somewhere/fileName*; do
       if [ -e "$path" ]; then   # handle wildcard possibly not matching
          sed "16 a file=$path" myScript.sh
       fi
    done
    

    不清楚如果通配符匹配多个文件会发生什么;也许您想在 fi 之前添加一个 break 以仅在发生这种情况时替换第一个。

    【讨论】:

    • 计算机可能不知道这一点,所以代码应该做正确的事情,即使它不知道。
    • 很好地理解了我认为的解决方案,我现在已将其删除,因为它不正确。
    • 循环是一个有趣的解决方案。有没有更简单的方法让 bash 扩展/插入字符串?
    • 你可以把它放在一个数组中,例如。
    • @user1934428 不,这不正确。 ideone.com/di5VT9
    【解决方案2】:

    这可能对你有用(GNU sed、echo 和 bash):

    export path='/path/toSomeWhere/filename*'
    sed '16{s/$/\na file=$(echo $path)/;s/.*/echo "&"/e}' file
    

    导出已设置为/path/toSomeWhere/filename* 的变量path(注意单引号会阻止插值)。

    file 的第 16 行附加一行 a file=$(echo $path),然后用双引号将这两行括起来,并在 echo 命令前面加上表达式(第二个替换命令上的 e 标志)。

    替代方案:

    sed '17e echo "a file=$(echo /path/toSomeWhere/filename*)"' file
    

    【讨论】:

      猜你喜欢
      • 2023-03-30
      • 2013-07-02
      • 1970-01-01
      • 2023-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-12
      • 1970-01-01
      相关资源
      最近更新 更多