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

ste*_*iny 7 bash 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"
            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"
Run Code Online (Sandbox Code Playgroud)

Cha*_*ffy 1

使用Pythonglob模块:

#!/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\0" % (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
Run Code Online (Sandbox Code Playgroud)