bash:处理(递归)目录中的所有文件

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

bash: processing (recursively) through all files in a directory

bashubuntu

提问by skyeagle

I want to write a bash script that (recursively) processes all files of a certain type.

我想编写一个 bash 脚本来(递归地)处理某种类型的所有文件。

I know I can get the matching file list by using find thusly:

我知道我可以通过使用 find 来获取匹配的文件列表:

find . -name "*.ext"

找 。-name "*.ext"

I want to use this in a script:

我想在脚本中使用它:

  1. recursively obatin list of files with a given extension
  2. obtain the full file pathname
  3. pass the full pathname to another script
  4. Check the return code from the script. If non zero, log the name of the file that could not be processed.
  1. 递归地获取具有给定扩展名的文件列表
  2. 获取完整的文件路径名
  3. 将完整路径名传递给另一个脚本
  4. 检查脚本的返回码。如果非零,则记录无法处理的文件的名称。

My first attempt looks (pseudocode) like this:

我的第一次尝试看起来(伪代码)是这样的:

ROOT_DIR = ~/work/projects
cd $ROOT_DIR
for f in `find . -name "*.ext"`
do
    #need to lop off leading './' from filename, but I havent worked out how to use
    #cut yet
    newname = `echo $f | cut -c 3
    filename = "$ROOT_DIR/$newname"

    retcode = ./some_other_script $filename

    if $retcode ne 0
       logError("Failed to process file: $filename")
done

This is my first attempt at writing a bash script, so the snippet above is not likely to run. Hopefully though, the logic of what I'm trying to do is clear enough, and someone can show how to join the dots and convert the pseudocode above into a working script.

这是我第一次尝试编写 bash 脚本,所以上面的代码片段不太可能运行。但希望我尝试做的事情的逻辑足够清晰,有人可以展示如何连接点并将上面的伪代码转换为工作脚本。

I am running on Ubuntu

我在 Ubuntu 上运行

回答by Ignacio Vazquez-Abrams

find . -name '*.ext' \( -exec ./some_other_script "$PWD"/{} \; -o -print \)

回答by tokland

Using | while readto iterate over file names is fine as long as there are no files with carrier return to be processed:

| while read只要没有要处理的承运人返回的文件,就可以使用迭代文件名:

find . -name '*.ext' | while IFS=$'\n' read -r FILE; do
  process "$(readlink -f "$FILE")" || echo "error processing: $FILE"
done