在 bash 脚本中使用 find 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8509226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using find command in bash script
提问by justuser
I just start to use bash script and i need to use find command with more than one file type.
我刚开始使用 bash 脚本,我需要使用具有多种文件类型的 find 命令。
list=$(find /home/user/Desktop -name '*.pdf')
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 ?
此代码适用于 pdf 类型,但我想一起搜索多个文件类型,如 .txt 或 .bmp。你有什么想法吗?
回答by ghoti
Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)
欢迎来到 bash。这是一个古老、黑暗而神秘的东西,能够施展巨大的魔法。:-)
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.
您要问的选项是针对find
命令的,而不是针对 bash 的。从命令行,您可以man find
查看选项。
The one you're looking for is -o
for "or":
您正在寻找的是-o
“或”:
list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"
That said ... Don't do this.Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLsfor details.
也就是说......不要这样做。像这样的存储可能适用于简单的文件名,但是一旦您必须处理特殊字符,如空格和换行符,所有赌注都将取消。有关详细信息,请参阅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
Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:
路径名扩展(通配)提供了一种更好/更安全的方式来跟踪文件。然后你也可以使用 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 FAQhas lots of other excellent tips about programming in bash.
该猛砸常见问题有很多关于bash编程等优秀的提示。
回答by Vivek Sethi
If you want to loop over what you "find", you should use this:
如果你想循环你“找到”的东西,你应该使用这个:
find . -type f -name '*.*' -print0 | while IFS= read -r -d '' file; do
printf '%s\n' "$file"
done
Source: https://askubuntu.com/questions/343727/filenames-with-spaces-breaking-for-loop-find-command
来源:https: //askubuntu.com/questions/343727/filenames-with-spaces-break-for-loop-find-command
回答by ash108
You can use this:
你可以使用这个:
list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')
Besides, you might want to use -iname
instead of -name
to catch files with ".PDF" (upper-case) extension as well.
此外,您可能还想使用-iname
而不是-name
捕获带有“.PDF”(大写)扩展名的文件。