小编ste*_*iny的帖子

将变量中的 shell glob 展开到数组中

在 bash 脚本中,我有一个包含 shell glob 表达式的变量,我想将其扩展为匹配文件名的数组(nullglob打开),例如

pat='dir/*.config'
files=($pat)
Run Code Online (Sandbox Code Playgroud)

即使对于$pat(eg, pat="dir/*.config dir/*.conf) 中的多个模式,这也很好用,但是,我不能在模式中使用转义字符。理想情况下,我希望能够做到

pat='"dir/*" dir/*.config "dir/file with spaces"'
Run Code Online (Sandbox Code Playgroud)

包含该文件,所有以和*结尾的文件。.configfile with spaces

是否有捷径可寻?(eval如果可能的话,没有。)

由于模式是从文件中读取的,因此我无法按照此答案(以及其他各个地方)中的建议将其直接放入数组表达式中。

编辑:

将事情放在上下文中:我想做的是逐行读取模板文件并处理所有行,例如#include pattern. 然后使用 shell glob 解析包含内容。由于该工具是通用的,因此我希望能够包含带有空格和奇怪字符(例如*)的文件。

“主”循环如下所示:

    template_include_pat='^#include (.*)$'
    while IFS='' read -r line || [[ -n "$line" ]]; do
        if printf '%s' "$line" | grep -qE "$template_include_pat"; then
            glob=$(printf '%s' "$line" | sed -nrE "s/$template_include_pat/\\1/p")
            cwd=$(pwd -P)
            cd "$targetdir" …
Run Code Online (Sandbox Code Playgroud)

bash glob

7
推荐指数
1
解决办法
2882
查看次数

标签 统计

bash ×1

glob ×1