使用Shell脚本查找特定文件类型的文件 [英] Find files of specific file types using shell script

查看:210
本文介绍了使用Shell脚本查找特定文件类型的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要递归遍历目录中某些文件类型的所有文件.文件类型是一个数组变量,其中包含我们需要进行处理的文件类型的列表.数组值实际上是动态填充的.为了简单起见,我声明一个静态数组.

I have a requirement to recursively loop through all the files of certain file types in a directory. The file types is an array variable containing the list of file types that we need to go through for processing. The array values are actually dynamically populated. For the sake of simplicity I am declaring a static array.

 declare -a arr=("pdf" "doc" "txt")

我有以下代码来递归列出目录中的所有文件,但是我无法弄清楚如何包含数组"arr"以仅取回数组中包含的那些文件类型.

I have the following code to recursively list all the files in the directory, but I am not able to figure out how include the array "arr" to only get back those file types that are included in the array.

find $i -type f -print0 | while read -d $'\0' file; do
    echo $file;
    #Process file
done

请帮助我修改代码,以便我只能检索指定的文件类型,而不能检索所有文件.

Please help me modify the code so that I could retrieve the specified file types only and not all files.

推荐答案

我假设通过文件类型"pdf","doc","txt",您的意思是带有这些扩展名的文件名.

I assume that by file types "pdf", "doc", "txt", you mean filenames with those extensions.

如果文件类型的数量很少(少于几十个),那么您可以构建一个参数数组,以以下格式传递给 find :

If the number of file types is reasonably small (less than a few dozen), then you could build an array of arguments to pass to find in the format:

... -name '*.pdf' -o -name '*.doc' -o -name '*.txt' ...

假设文件类型数组不为空,这是一种处理方法(感谢 @ mike-holt ):

Assuming that the array of file types is not empty, here's one way to do it (thanks @mike-holt):

arr=(pdf doc txt)

findargs=()

for t in "${arr[@]}"; do
    findargs+=(-name "*.$t" -o)
done

find . -type f \( "${findargs[@]}" -false \)

这篇关于使用Shell脚本查找特定文件类型的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆