对所有类似文件运行 Bash while 循环

对所有类似文件运行 Bash while 循环

我想在 Bash 中编写一个 while 循环,遍历所有以下形式的文件实例

{number}.tst

例如,1.tst2.tst, ... 50.tst

我愿意不是希望它能运行该文件tst.tst

我该如何编写此代码?我假设我需要一个布尔短语[0-9]*,但语法并不完全确定。

答案1

如果你只需要排除像你的例子那样的字母名称,tst.tst你可以使用一个简单的 shell glob

for f in [0-9]*.tst; do echo "$f"; done

使用 bash扩展的 glob(Ubuntu 中默认启用该功能)

给定

$ ls *.tst
1.tst  2.tst  3.tst  4.tst  50.tst  5.tst  bar.tst  foo.tst

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

您可以使用 检查扩展通配符是否已启用,shopt extglob并在必要时使用进行设置shopt -s extglob(并使用 取消设置set -u extglob)。

答案2

由此堆栈溢出回答:列出名称中只有数字的文件

find . -regex '.*/[0-9]+\.tst'

或者

当您想对文件执行某些操作时,使用 find 也具有优势,例如使用内置的-exec-print0以及管道xargs -0或甚至(使用 Bash):

while IFS='' read -r -d '' file
do
  # ...
done < <(find . -regex '.*/[0-9]+\.tst' -print0)

请注意,如果文件名以数字开头,此处的其他答案可能会包含非数字的文件。但此处发布的答案并非如此。例如:

$ ls *.tst
12tst.tst  1.tst  2.tst

$ find . -maxdepth 1 -regex '.*/[0-9]+\.tst'
./1.tst
./2.tst

笔记:使用-maxdepth 1参数仅列出当前目录中的编号文件,而不是子目录中的编号文件。

答案3

在这种情况下,没有格式为 {number}{non-number}.tst 的文件名,因此一个可能的解决方案是包含所有文件名开始使用数字:

for filename in [0-9]*.tst; do
    echo "$filename"  # Example command
done

答案4

如果您想按数字顺序处理文件,可以使用命令seq(read man seq)。

for i in $( seq 1 50 ) ; do
    echo "Process ${i}.txt"
done

相关内容