在Bash脚本中使用find命令

30

我刚开始使用Bash脚本,需要使用find命令来查找多个文件类型。

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

这段代码适用于PDF类型的文件,但我想同时搜索多种文件类型,比如.txt或.bmp文件。你有什么想法吗?

3个回答

50

欢迎来到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中编程的许多其他优秀提示。


14

4
你可以使用这个:
list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')

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

3
为了处理文件名中包含空格的情况,您需要在后面的$list变量中使用引号,例如for i in "$list"; do echo $i; done。如果没有双引号,您的脚本将把"文件名 like this.jpg"看作三个文件:"文件名"、 "like" 和 "this.jpg"。 - ash108

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接