BASH - 文件名中的任何字符替换

时间:2014-12-17 08:03:57

标签: bash

我有一些文件。模式看起来像这样:

FILE_1.TXT
FILE_2.TXT
FILE_3.TXT

现在我有一个循环,我想对这些文件做些什么。出于某种原因(原因对于这个问题并不重要),我必须不通过*.TXT而是通过FILE_*.TXT来运行循环 - 文件名中只有一个变化就是数字。 FILE_*.TXT无效,Bash正在寻找FILE_*.TXT而不是FILE_1.TXT等。

我使用的代码如下所示:

for file in FILE_*.TXT
    do
# doing some stuff with the files
    done

我怎样才能使这个工作?

3 个答案:

答案 0 :(得分:4)

从这个循环中获得FILE_*.TXT的唯一方法是,如果这些文件中没有一个存在:

$ for file in FILE_*.TXT;do echo $file; done
FILE_*.TXT

$ touch FILE_7.TXT

$ for file in FILE_*.TXT;do echo $file; done
FILE_7.TXT

因此,我建议您仔细查看模式并确保存在 这些文件。

答案 1 :(得分:1)

正如paxdiablo已经提到的,你没有任何与该模式相匹配的文件 您可以设置名为nullglob

的shell选项
$ for x in *.doesnotexist; do echo $x; done
*.doesnotexist

$ shopt -s nullglob

$ for x in *.doesnotexist; do echo $x; done
$ (Nothing is printed, the loop does not run.)

答案 2 :(得分:0)

一切正常:

$ ls
FILE_1.TXT  FILE_2.TXT  FILE_3.TXT
$ for f in FILE_*.TXT
do
  echo $f
done
FILE_1.TXT
FILE_2.TXT
FILE_3.TXT

提示: file是一个现有工具:

$ file
Usage: file [-bchikLlNnprsvz0] [--apple] [--mime-encoding] [--mime-type]
            [-e testname] [-F separator] [-f namefile] [-m magicfiles] file ...
       file -C [-m magicfiles]
       file [--help]

使用其他变量名称,例如f

相关问题