【问题标题】:Matching files with various extensions using for loop [duplicate]使用for循环匹配具有各种扩展名的文件[重复]
【发布时间】:2011-06-03 06:39:49
【问题描述】:

我正在尝试匹配并循环通过扩展名为 .txt .h .py 的文件。在特定文件夹 ${arg} 中。这就是我所做的

for file in ${arg}/*.{txt, h, py}; do
  ...

done

但是,即使我有这样的文件,我也没有得到所有扩展名的这样的文件。

 line 24: dir1/*.{txt,: No such file or directory
 line 24: h,: No such file or directory
 line 24: py}: No such file or directory

如何使用for 循环浏览具有指定扩展名的文件?

【问题讨论】:

    标签: bash


    【解决方案1】:

    去掉空格; bash 关心。

    for file in "${arg}"/*.{txt,h,py}; do
    

    【讨论】:

      【解决方案2】:

      我想对提议的解决方案提出 2 项改进建议:

      A. "$arg"/.{txt,h,py} 中的 for 文件也将产生 "$arg"/.txt 如果没有带有 txt 扩展名的文件并且使用脚本创建错误:

      $ echo *.{txt,h,py}
      *.txt *.h doSomething.py
      

      为避免这种情况,在 for 循环之前,设置 nullglob 以从列表中删除 null glob:

      $ shopt -s nullglob # Sets nullglob
      $ echo *.{txt,h,py}
      doSomething.py
      $ shopt -u nullglob # Unsets nullglob
      

      B.如果您还想搜索 *.txt 或 *.TXT 甚至 *.TxT(即忽略大小写),那么您还需要设置 nocaseglob:

      $ shopt -s nullglob # Sets nullglob
      $ shopt -s nocaseglob # Sets nocaseglob
      $ echo *.{txt,h,py}
      myFile.TxT doSomething.py
      $ shopt -u nocaseglob # Unsets nocaseglob
      $ shopt -u nullglob # Unsets nullglob
      

      【讨论】:

        【解决方案3】:

        正如 Ignacio 已经告诉您应该删除空格。如果您也想对子目录递归地执行此操作,请使用双 ** globbing:

        for file in ${arg}/**/*.{txt,h,py}
        do
            ....
        done
        

        ps:仅适用于 bash4

        【讨论】:

        • 如果启用了globstar
        猜你喜欢
        • 2013-05-17
        • 2015-05-31
        • 1970-01-01
        • 2014-02-05
        • 1970-01-01
        • 1970-01-01
        • 2016-09-01
        • 1970-01-01
        • 2016-07-23
        相关资源
        最近更新 更多