【问题标题】:for loop over specific files in a directory using Bashfor 使用 Bash 遍历目录中的特定文件
【发布时间】:2013-01-27 05:52:21
【问题描述】:

在一个目录中,您有一些不同的文件 - .txt.sh,然后计划不带 .foo 修饰符的文件。

如果你ls目录:

blah.txt
blah.sh
blah
blahs

如何告诉 for 循环只使用没有 .foo 修改的文件?因此,在上面的示例中,对文件 blah 和 blahs 进行“处理”。

基本语法是:

#!/bin/bash
FILES=/home/shep/Desktop/test/*

for f in $FILES
do
    XYZ functions
done

如您所见,这有效地循环了目录中的所有内容。如何排除 .sh.txt 或任何其他修饰符?

我一直在玩一些 if 语句,但我真的很好奇我是否可以选择那些未修改的文件。

还有人可以告诉我这些没有 .txt 的纯文本文件的正确术语吗?

【问题讨论】:

    标签: bash for-loop


    【解决方案1】:
    #!/bin/bash
    FILES=/home/shep/Desktop/test/*
    
    for f in $FILES
    do
    if [[ "$f" != *\.* ]]
    then
      DO STUFF
    fi
    done
    

    【讨论】:

    • 这适用于我的修改形式。我的一些文件名包含“.'s”,所以使用 \. 仍然可以选择它们。你的代码用什么 fi ?谢谢!
    • 这只是 bash 的结束符(如果向后)。
    • 嗯,这就是为什么 'done' 会引发错误,需要关闭 if 语句。很酷,谢谢。
    【解决方案2】:

    如果你想让它更复杂一点,你可以使用 find-command。

    对于当前目录:

    for i in `find . -type f -regex \.\\/[A-Za-z0-9]*`
    do
    WHAT U WANT DONE
    done
    

    解释:

    find . -> starts find in the current dir
    -type f -> find only files
    -regex -> use a regular expression
    \.\\/[A-Za-z0-9]* -> thats the expression, this matches all files which starts with ./
    (because we start in the current dir all files starts with this) and has only chars
    and numbers in the filename.
    

    http://infofreund.de/bash-loop-through-files/

    【讨论】:

      【解决方案3】:

      您可以使用负通配符吗?过滤掉它们:

      $ ls -1
      a.txt
      b.txt
      c.png
      d.py
      $ ls -1 !(*.txt)
      c.png
      d.py
      $ ls -1 !(*.txt|*.py)
      c.png
      

      【讨论】:

      • 好的,但是假设我有一个包含两个以上的目录。有没有一种合乎逻辑的方法可以让 bash 为我做到这一点?这样它就可以应用于大多数目录,同时以相同的方式工作。
      • @jon_shep:两个以上什么?
      • 文件扩展名。在您的示例中,您必须手动排除它们。
      • !(*.*),不,这不是 POSIX。
      • 您还需要设置extglob 选项才能使其工作:shopt -s extglob
      猜你喜欢
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-25
      • 2021-01-16
      • 2014-10-02
      • 1970-01-01
      • 2019-01-16
      相关资源
      最近更新 更多