Bash 脚本:查找所有文件类型和路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1131936/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 21:03:38  来源:igfitidea点击:

Bash scripting: Find all filetypes and paths

linuxbashsearchdirectory

提问by unwind

Using Bash, how can you traverse folders within specified folder, find all files of specified file type, and every time you find a file, get full file path with file name and full file path without file name as a variables and pass them to another Bash script, execute it, and continue searching for the next file?

使用Bash,如何遍历指定文件夹内的文件夹,查找指定文件类型的所有文件,并且每次找到文件时,获取带文件名的完整文件路径和不带文件名的完整文件路径作为变量并传递给另一个Bash 脚本,执行它,然后继续搜索下一个文件?

回答by unwind

Assuming a GNU find(which is not unreasonable) you can do this using just find:

假设GNU 查找(这并非不合理),您可以仅使用查找来执行此操作:

find /path -type f -name '*.ext' -exec my_cool_script \{\} \;

回答by neuro

find is the way. Using xargs handle long list of files/dirs. Moreover to handle correctly names with spaces and problem like that, the best find line command I've found is :

找到就是办法。使用 xargs 处理文件/目录的长列表。此外,为了正确处理带有空格和类似问题的名称,我发现的最好的 find 行命令是:

find ${directory} -name "${pattern}" -print0 | xargs -0 ${my_command}

The trick is the find -print0 that is compatible with the xargs -0 : It replace endlines by '\0' to correctly handle spaces and escape characters. Using xargs spares you some "line too long" message when your filelist is too long.

诀窍是 find -print0 与 xargs -0 兼容:它将结束行替换为 '\0' 以正确处理空格和转义字符。当您的文件列表太长时,使用 xargs 可以为您节省一些“行太长”的消息。

You can use xargs with --no-run-if-empty to handle empty lists and --replace to manage complex commands.

您可以将 xargs 与 --no-run-if-empty 一起使用来处理空列表,并使用 --replace 来管理复杂的命令。

回答by Ole Tange

If you have GNU Parallel http://www.gnu.org/software/parallel/installed you can do this:

如果您安装了 GNU Parallel http://www.gnu.org/software/parallel/,您可以这样做:

find . -name '*.ext' | parallel echo {} '`dirname {}`'

Substitute echowith your favorite bash command and ext with the file extension you are looking for.

echo用您最喜欢的 bash 命令替换,用您要查找的文件扩展名替换ext。

Watch the intro video for GNU Parallel to learn more: http://www.youtube.com/watch?v=OpaiGYxkSuQ

观看 GNU Parallel 的介绍视频以了解更多信息:http: //www.youtube.com/watch?v=OpaiGYxkSuQ

回答by ghostdog74

looks very much like homework.

看起来很像家庭作业。

find /path -type f -name "*.ext" -printf "%p:%h\n" | while IFS=: read a b
do
   # execute your bash script here
done

read the man page of find for more printf options....

阅读 find 的手册页以获取更多 printf 选项....