在所有类似文件上循环运行Bash
我想在Bash中编写一个while循环,它运行在所有forms的文件实例上
{number}.tst
例如, 1.tst
, 2.tst
,… 50.tst
。
我不希望它在文件tst.tst
上运行。
我该怎么写呢? 我假设我需要一个布尔短语和[0-9]*
在那里,但我不完全确定语法。
如果您只需要像示例tst.tst
那样排除字母名称,则可以使用简单的shell glob
for f in [0-9]*.tst; do echo "$f"; done
使用bash 扩展globs (默认情况下应该在Ubuntu中启用)
特定
$ ls *.tst 1.tst 2.tst 3.tst 4.tst 50.tst 5.tst bar.tst foo.tst
那么+([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
检查是否启用了扩展globbing,并在必要时使用shopt -s extglob
设置它(并使用set -u extglob
取消set -u extglob
)。
从此Stack Overflow回答: 列出仅在名称中包含数字的文件 :
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
参数仅列出当前目录中的编号文件,而不是子目录中的编号文件。
在这种情况下,没有{number} {non-number} .tstforms的文件名,因此一种可能的解决方案是包含所有以数字开头的文件名:
for filename in [0-9]*.tst; do echo "$filename" # Example command done
如果seq
数字顺序处理文件,则有seq
命令(read man seq
)。
for i in $( seq 1 50 ) ; do echo "Process ${i}.txt" done