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

Expand shell glob in variable into array

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

pat='dir/*.config'
files=($pat)

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

pat='"dir/*" dir/*.config "dir/file with spaces"'

包含文件 *,所有以 .configfile with spaces.

结尾的文件

有没有简单的方法来做到这一点? (如果可能,没有 eval。)

由于模式是从文件中读取的,所以我不能将它直接放在数组表达式中,as proposed in this answer(以及其他各种地方)。

编辑:

将事情放在上下文中:我正在尝试做的是逐行读取模板文件并处理所有行,如 #include pattern。然后使用 shell glob 解析包含。因为这个工具是通用的,所以我希望能够包含带有空格和奇怪字符的文件(比如 *)。

"main" 循环如下所示:

    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"
            files=($glob)
            for f in "${files[@]}"; do
                printf "\n\n%s\n" "# FILE $f" >> "$tempfile"
                cat "$f" >> "$tempfile" ||
                    die "Cannot read '$f'."
            done
            cd "$cwd"
        else
            echo "$line" >> "$tempfile"
        fi
    done < "$template"

使用 Python glob 模块:

#!/usr/bin/env bash

# Takes literal glob expressions on as argv; emits NUL-delimited match list on output
expand_globs() {
  python -c '
import sys, glob
for arg in sys.argv[1:]:
  for result in glob.iglob(arg):
    sys.stdout.write("%s[=10=]" % (result,))
' _ "$@"
}

template_include_pat='^#include (.*)$'
template=${1:-/dev/stdin}

# record the patterns we were looking for
patterns=( )

while read -r line; do
  if [[ $line =~ $template_include_pat ]]; then
    patterns+=( "${BASH_REMATCH[1]}" )
  fi
done <"$template"

results=( )
while IFS= read -r -d '' name; do
  results+=( "$name" )
done < <(expand_globs "${patterns[@]}")

# Let's display our results:
{
  printf 'Searched for the following patterns, from template %q:\n' "$template"
  (( ${#patterns[@]} )) && printf ' - %q\n' "${patterns[@]}"
  echo
  echo "Found the following files:"
  (( ${#results[@]} )) && printf ' - %q\n' "${results[@]}"
} >&2