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

标签 bash glob

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

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

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

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

包括文件 *,所有以 .config 结尾的文件和 带空格的文件

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

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

编辑:

将事情放在上下文中:我正在尝试做的是逐行读取模板文件并处理所有行,如 #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"

最佳答案

使用 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\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

关于bash - 将变量中的 shell glob 扩展到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48524311/

相关文章:

bash - 使用 curl 循环访问 url 的 Shell 脚本

linux - 在命令行中复制一系列文件夹

python - ValueError : could not convert string to float: 'samples.txt'

javascript - 哪个 C 库具有执行 zsh 的递归 glob 的功能?

linux - 反向合并文件

Bash 列表理解或映射

bash - 使用管道时修改文件的最佳方法?

linux - 检查参数是文件还是目录

c - Glob 与用户提供的目录?

shell - 我怎样才能将所有嵌套文件与子目录异常(exception)