【问题标题】:Iterate over files in a subfolder遍历子文件夹中的文件
【发布时间】:2023-01-20 18:14:36
【问题描述】:

新来的,第一次学习 bash。 我正在尝试遍历放置在子文件夹中的名为“list.txt”的文件,在同一子文件夹下操作和创建新文件。鸟巢可能是这样的: inventory/product_names1/list.txt inventory/product_names2/list.txt 由于 product_names 是完全随机的,我想使用 unix cms(如 sed/grep/cut)遍历所有 list.txt 文件,并在相同的随机 product_names 文件夹下创建一个新文件。

for f in $( find . -name 'list.txt');为 $f 中的列表做;做猫 $f | cut -d']' -f2- > "$f/new_file.txt" ;完毕 ;完毕

我可以使用 find 命令将文件访问到嵌套中。如果 product_names 是随机的,我如何在正确的子文件夹中重定向输出?

inventory/product_names1/list.txt inventory/product_names1/new_file.txt inventory/product_names2/list.txt inventory/product_names2/new_file.txt

此脚本旨在在根文件夹中工作,指向并使用时间路径“inventory”。 $f 访问 inventory/product_names1/list.txt 但我需要 inventory/product_names1 中的输出。如果我没有正确的值/变量,我该如何正确重定向?

【问题讨论】:

    标签: bash loops path


    【解决方案1】:

    您可以使用参数扩展从路径中删除文件名,或者您可以遍历所有目录并仅在它们包含 list.txt 文件时处理它们。

    #!/bin/bash
    for list in inventory/*/list.txt ; do
        new=${list%/*}/new_list.txt
        echo "$list" "$new"
    done
    
    # OR
    
    for dir in inventory/* ; do
        if [[ -f $dir/list.txt ]] ; then
            echo "$dir"/list.txt "$dir"/new_list.txt
        fi
    done
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-28
      • 2018-12-20
      • 2017-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      相关资源
      最近更新 更多