在bash脚本中使用find命令 [英] Using find command in bash script
问题描述
我刚刚开始使用bash脚本,我需要使用具有多种文件类型的find命令.
I just start to use bash script and i need to use find command with more than one file type.
list=$(find /home/user/Desktop -name '*.pdf')
此代码适用于pdf类型,但我想一起搜索多个文件类型,例如.txt或.bmp.您有任何想法吗?
this code work for pdf type but i want to search more than one file type like .txt or .bmp together.Have you any idea ?
推荐答案
欢迎使用bash.这是一件古老,黑暗而神秘的东西,具有强大的魔力. :-)
Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)
您要询问的选项是find
命令,而不是bash.在命令行中,您可以man find
查看选项.
The option you're asking about is for the find
command though, not for bash. From your command line, you can man find
to see the options.
您要查找的是-o
表示或":
The one you're looking for is -o
for "or":
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数组:
Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:
$ 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编程的优秀技巧.
The Bash FAQ has lots of other excellent tips about programming in bash.
这篇关于在bash脚本中使用find命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!