gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:29:24 24 4
gpt4 key购买 nike

在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com