【问题标题】:Bash: Look for files in certain folders and then create output listsBash:在某些文件夹中查找文件,然后创建输出列表
【发布时间】:2016-10-22 06:55:57
【问题描述】:

我是 Bash 新手,我正在尝试在一组特定文件夹中查找文件。我想为每个 /check/ 文件夹中的图像文件创建一个 txt 报告。

这是我一直在使用的:

# Find images
for f in */check/ ; do
    find ./ -iname "*jpg*" -o -iname "*png*" > find_images.txt
        echo "finished $f"
done

我不知道如何只查看名为“check”的子文件夹,我还想传递变量,以便获得以父文件夹命名的单独文本文件。有什么建议吗?

【问题讨论】:

  • 如果您想从for 循环中搜索check 目录,请使用find "$f" 而不是find ./。在这种情况下,您还必须修复重定向,以避免不断覆盖相同的 find_images.txt

标签: bash shell


【解决方案1】:

您很接近,但您没有使用包含文件夹名称的$f

# Find images
for f in */check/ ; do
    # Removing front-slashes from $f to use in log name
    # http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion
    log_f="${f//\//_}"

    # Only search inside $f, saving results to find_images_[foldername].txt
    find "$f" -iname "*jpg*" -o -iname "*png*" > "find_images_${log_f}.txt"

    echo "finished $f"
done

【讨论】:

    【解决方案2】:

    使用 grep 命令 并使用 find 命令

    进行管道传输
    find . | grep check 
    

    【讨论】:

    • find . -type f -regex ".*\.\(jpg\|gif\|png\|jpeg\)" | grep check
    【解决方案3】:

    find命令支持搜索目录(文件夹),例如

    find . -name "check" -type d
    

    您可以使用这些结果来查找您想要的文件。变量 $f 将是文件夹的名称,因此请在内部 find 命令中使用它。然后,如果您希望每次通过循环都有单独的输出文件,请在文件名中使用一个变量。 $f 变量将在内容中包含斜杠,因此您可能不想在输出文件的名称中使用它。在我的示例中,我使用了一个计数器来确保每个输出文件都有一个唯一的名称。

    count=1
    for f in `find . -name "check" -type d` ; do
        find $f -iname "*jpg*" -o -iname "*png*" > find_images_$count_.txt
        count=$((count+1))
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2016-11-11
      • 2017-04-05
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      相关资源
      最近更新 更多