循环遍历给定目录中的所有文件

时间:2011-02-28 04:16:12

标签: shell

这是我正在尝试做的事情:

为shell脚本提供一个参数,该脚本将在jpg,bmp,tif扩展名的所有文件上运行任务。

例如:./ doProcess / media / repo / user1 / dir5

该目录中的所有jpg,bmp,tif文件都将运行某个任务。

我现在拥有的是:

for f in *
do
  imagejob "$f"  "output/${f%.output}" ;
done

我需要帮助for循环来限制文件类型,并且还有一些在指定目录而不是当前目录下启动的方法。

4 个答案:

答案 0 :(得分:6)

使用shell扩展而不是ls

for file in *.{jpg,bmp,tif}
do
  imagejob "$file" "output/${file%.output}"
done

如果你有bash 4.0+,你可以使用globstar

shopt -s globstar
shopt -s nullglob
shopt -s nocaseglob
for file in **/*.{jpg,bmp,tif}
do
  # do something with $file
done

答案 1 :(得分:0)

for i in `ls $1/*.jpg $1/*.bmp $1/*.tif`; do
    imagejob "$i";
done

这假设你正在使用一个类似于bash的shell,其中$1是给它的第一个参数。

你也可以这样做:

find "$1" -iname "*.jpg" -or -iname "*.bmp" -or -iname "*.tif" \
          -exec imagejob \{\} \;

答案 2 :(得分:0)

您可以使用带反引号和ls(或任何其他突击队)的构造:

for f in `ls *.jpg *.bmp *.tif`; do ...; done

答案 3 :(得分:0)

这里的其他解决方案是仅使用Bash或建议使用ls,尽管它是a common and well-documented antipattern。以下是在不使用sh的POSIX ls中解决此问题的方法:

for file in *.jpg *.bmp *.tif; do
    ... stuff with "$file"
done

如果文件数量很多,也许您还想研究

find . -maxdepth -type f \( \
    -name '*.jpg' -o -name '*.bmp' -o -name '*.tif' \) \
    -exec stuff with {} +

避免了按字母顺序对文件名进行排序的开销。 -maxdepth 1表示不递归到子目录中;显然,如果要递归到子目录中,请删除或修改它。

-exec ... +的{​​{1}}谓词是一个相对较新的介绍;如果您的find过老,则可能要使用find或将-exec ... \;替换为

-exec stuff with {} +

然而,find ... -print0 | xargs -r0 stuff with 选项和-print0对应的-0选项还是GNU扩展。

相关问题