我想在 Bash 中编写一个 while 循环,它运行在以下形式的文件的所有实例上
{number}.tst
Run Code Online (Sandbox Code Playgroud)
例如,1.tst, 2.tst, ... 50.tst.
我不希望它运行在文件上tst.tst。
我该怎么写这个?我想我需要一个布尔短语和[0-9]*某个地方,但我不完全确定语法。
如果您只需要像示例一样排除字母名称tst.tst,则可以使用简单的 shell glob
for f in [0-9]*.tst; do echo "$f"; done
Run Code Online (Sandbox Code Playgroud)
使用 bash扩展的 globs(在 Ubuntu 中默认启用)
给予
$ ls *.tst
1.tst 2.tst 3.tst 4.tst 50.tst 5.tst bar.tst foo.tst
Run Code Online (Sandbox Code Playgroud)
then+([0-9])表示一位或多位十进制数字:
for f in +([0-9]).tst; do echo "$f"; done
1.tst
2.tst
3.tst
4.tst
50.tst
5.tst
Run Code Online (Sandbox Code Playgroud)
您可以检查是否启用了扩展通配符shopt extglob,并在必要时使用shopt -s extglob(并使用 取消设置set -u extglob)进行设置。
从这个堆栈溢出答案:列出名称中只有数字的文件:
find . -regex '.*/[0-9]+\.tst'
Run Code Online (Sandbox Code Playgroud)
或者
当你想对文件做一些事情时,使用 find 也有好处,例如使用内置的-exec,-print0和管道xargs -0甚至(使用 Bash):
while IFS='' read -r -d '' file
do
# ...
done < <(find . -regex '.*/[0-9]+\.tst' -print0)
Run Code Online (Sandbox Code Playgroud)
请注意此处的其他答案,如果文件名以数字开头,则我包含的文件不是数字。但是,此处发布的答案没有。例如:
$ ls *.tst
12tst.tst 1.tst 2.tst
$ find . -maxdepth 1 -regex '.*/[0-9]+\.tst'
./1.tst
./2.tst
Run Code Online (Sandbox Code Playgroud)
注意:使用-maxdepth 1参数仅列出当前目录中的编号文件,而不是子目录中的文件。