我刚刚开始使用 bash 脚本,并且需要对多种文件类型使用 find 命令。
list=$(find /home/user/Desktop -name '*.pdf')
此代码适用于 pdf 类型,但我想同时搜索多种文件类型,例如 .txt 或 .bmp。您有什么想法吗?
欢迎来到巴什。这是一种古老、黑暗、神秘的东西,具有强大的魔力。 :-)
您询问的选项是针对find
但命令不适用于 bash。从命令行,您可以man find
查看选项。
您正在寻找的是-o
对于“或”:
list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"
那是说...不要这样做。像这样的存储可能适用于简单的文件名,但是一旦您必须处理特殊字符(例如空格和换行符),所有的赌注都会消失。看解析L http://mywiki.wooledge.org/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
路径名扩展(通配符)提供了一种更好/更安全的方式来跟踪文件。然后你还可以使用 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
The Bash FAQ http://mywiki.wooledge.org/BashFAQ还有许多关于 bash 编程的其他精彩技巧。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)