Globbing:将文件名与脚本中的数字匹配?

Globbing: Matching files names with a number in a script?

我想匹配目录中的所有文件名,如下所示:

h1.txt, h2.txt, h12.txt, h3.txt

假设目录是test/。我有一个名为 test.sh 的脚本,其中包含以下内容:

p=test/h
echo $p+([[:digit:]]).txt

但这给出了一个错误:

./test.sh: line 2: syntax error near unexpected token '(' ./test.sh:

line 2: 'echo $p+([[:digit:]]).txt'

有人能解释一下这是怎么回事吗?这在控制台中工作正常,请参阅

我建议使用 find:

find test -type f -regex '.*h[0-9]+.txt'

原始(过时)答案:

使用范围可能适合您:

echo test/h{1..99}.txt

您只需启用 extglob 即可使该 glob 表达式起作用:

shopt -s extglob

p='test/h'
echo "$p"+([[:digit:]]).txt

输出:

test/h1.txt test/h12.txt test/h2.txt test/h3.txt