在bash脚本中使用find命令

时间:2011-12-14 17:49:01

标签: find command

我刚开始使用bash脚本,我需要使用具有多种文件类型的find命令。

list=$(find /home/user/Desktop -name '*.pdf') 

此代码适用于pdf类型,但我想一起搜索多个文件类型,如.txt或.bmp。有什么想法吗?

3 个答案:

答案 0 :(得分:32)

欢迎来到bash。这是一个古老,黑暗和神秘的东西,能够产生巨大的魔力。 : - )

您要问的选项是find命令,而不是bash。在命令行中,您可以man find查看选项。

您正在寻找的是-o代表“或”:

  list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"

那说... 不要这样做。 这样的存储可能适用于简单的文件名,但只要你需要处理特殊字符,比如空格和换行符,所有投注均已关闭。有关详细信息,请参阅ParsingLs

$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt

路径名扩展(globbing)提供了一种更好/更安全的方式来跟踪文件。然后你也可以使用bash数组:

$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 one.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 two three.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 foo.bmp

Bash FAQ还有很多关于bash编程的优秀技巧。

答案 1 :(得分:7)

如果您想要查找"找到",您应该使用它:

find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
    printf '%s\n' "$file"
done

来源:https://askubuntu.com/questions/343727/filenames-with-spaces-breaking-for-loop-find-command

答案 2 :(得分:3)

您可以使用:

list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')

此外,您可能希望使用-iname而不是-name来捕获带有“.PDF”(大写)扩展名的文件。