我如何编写一个bash脚本,遍历parent_directory内的每个目录,并在每个目录中执行命令。

目录结构如下:

Parent_directory(名称可以是任何东西-不遵循模式) 001(目录名称遵循此模式) 0001.txt(文件名遵循此模式) 0002.三种 0003.三种 002 0001.三种 0002.三种 0003.三种 0004.三种 003 0001.三种 目录数量未知。


当前回答

你可以使用

find .

递归搜索当前目录下的所有文件/dirs

然后您可以像这样通过xargs命令输出

find . | xargs 'command here'

其他回答

for p in [0-9][0-9][0-9];do
    (
        cd $p
        for f in [0-9][0-9][0-9][0-9]*.txt;do
            ls $f; # Your operands
        done
    )
done

我不明白文件的格式,因为你只想遍历文件夹…你在找这样的东西吗?

cd parent
find . -type d | while read d; do
   ls $d/
done
for dir in PARENT/*
do
  test -d "$dir" || continue
  # Do something with $dir...
done

您可以通过管道,然后使用xargs来实现这一点。问题是您需要使用-I标志,它将用每个xargs传递的子字符串替换bash命令中的子字符串。

ls -d */ | xargs -I {} bash -c "cd '{}' && pwd"

您可能希望将pwd替换为您想在每个目录中执行的任何命令。

你可以使用

find .

递归搜索当前目录下的所有文件/dirs

然后您可以像这样通过xargs命令输出

find . | xargs 'command here'