我刚开始使用bash脚本,我需要使用find命令以及多种文件类型。在bash脚本中使用find命令
list=$(find /home/user/Desktop -name '*.pdf')
为PDF类型此代码的工作,但我想搜索多个文件类型像.txt或.BMP together.Have你什么想法?
我刚开始使用bash脚本,我需要使用find命令以及多种文件类型。在bash脚本中使用find命令
list=$(find /home/user/Desktop -name '*.pdf')
为PDF类型此代码的工作,但我想搜索多个文件类型像.txt或.BMP together.Have你什么想法?
欢迎来到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编程等优秀的提示。
您可以使用此:
list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')
此外,你可能想使用的-iname
代替-name
赶上文件与“.PDF”(大写)扩展为好。
如果你想遍历你“发现”什么,你应该使用这样的:
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`后面的变量,就像在`for $ in“$ list”;做echo $ i; done`。如果没有双引号,脚本会将每个“像this.jpg这样的文件名”视为三个文件:“filename”,“like”和“this.jpg”。 – ash108 2011-12-16 06:58:02