首页 > 解决方案 > Sed 没有在变量中扩展 *

问题描述

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

这里的目标是找到相应文件的路径,然后将该路径添加到脚本的第 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)$path在传递给 sed 之前包含完全扩展的字符串的方法。

标签: linuxbashunixsed

解决方案


您的变量只包含一个字符串,然后您插入该字符串。sed不知道这不是你的意思。如果您希望外壳(不是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

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


推荐阅读