我刚开始使用Bash脚本,需要使用find命令来查找多个文件类型。
list=$(find /home/user/Desktop -name '*.pdf')
这段代码适用于PDF类型的文件,但我想同时搜索多种文件类型,比如.txt或.bmp文件。你有什么想法吗?
欢迎来到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中编程的许多其他优秀提示。
如果你想循环遍历你所“发现”的东西,你应该使用这个:
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
list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')
-iname
而不是-name
来捕捉扩展名为“.PDF”(大写字母)的文件。
$list
变量中使用引号,例如for i in "$list"; do echo $i; done
。如果没有双引号,您的脚本将把"文件名 like this.jpg"看作三个文件:"文件名"、 "like" 和 "this.jpg"。 - ash108