gpt4 book ai didi

linux - 如何遍历给定目录的所有子目录?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:39:09 25 4
gpt4 key购买 nike

我编写了一个脚本,直接报告当前目录中的文件。我想扩展我的脚本,让它遍历所有的子目录和子目录的子目录等等,并做一个整体的报告。

例如:

enter image description here

my_script > report

创建如下报告:

HEADERS += \ 
header1.h \
header2.h \

SOURCES += \
source1.cpp \
source2.cpp \

但是让我们想象一下我们有子文件夹:

enter image description here

我想做一个递归报告:

INCLUDEPATH += "relative path to subfolder1"

"result of my_script for subfolder1"

INCLUDEPATH += "relative path to subfolder2"

"result of my_script for subfolder2"

HEADERS += \
header1.h \
header2.h \

SOURCES += \
source1.cpp \
source2.cpp \

我试图查看类似的问题,但所有这些问题在本质上似乎都不相同,并且都由一行 linux 命令回答。我认为我的问题更复杂,因为脚本需要递归调用自身。

编辑:这是我的脚本:

#!/bin/bash

if ls *.h &> /dev/null; then
echo "HEADERS += \ "
printf ' %s \\\n' *.h
echo ""
fi

if ls *.cpp &> /dev/null; then
echo "SOURCES += \ "
printf ' %s \\\n' *.cpp
echo ""
fi

if ls *.ui &> /dev/null; then
echo "FORMS += \ "
printf ' %s \\\n' *.ui
fi

最佳答案

I think that my problem is more complicated, since the script needs to call itself recursively.

是否需要递归,还是需要每次都调用一次目录?这个片段应该允许后者:

find ${top:?} -type d | while read dir; do
(cd $dir && ${name_of_script:?})
done

注意:为变量 top(树的顶部)和 name_of_script 添加合适的值。它们已使用 ${var:?} 进行编码以捕获未设置的变量并允许代码段失败优雅地。

关于linux - 如何遍历给定目录的所有子目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18761887/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com