在当前目录的每个子目录中,我想打印子目录及其子目录中所有文件的字符串的行匹配数。
例如,如果我有
cat /folder/a/file1.txt
test
x
x
cat /folder/a/file2.txt
x
test
x
test
cat /folder/b/c/file3.txt
x
test
x
test
我想查看in/folder
及其所有子目录的出现次数。每个目录一行。预期输出:
/folder: 4
/folder/a: 3
/folder/b: 1
/folder/b/c: 1
答案1
这是另一个技巧;它滥用 stderr 来打印结果,因为它使用 stdout 从任何子目录捕获递归总计。
function countdirhelper {
count=0
string=$1
for f in *
do
if [ -f "$f" ]
then
add=$(grep -c -- "$string" "$f")
elif [ -d "$f" ]
then
add=$(cd "$f"; countdirhelper "$string")
fi
count=$((count + add))
done
printf "%s: %d\n" "$PWD" "$count" >&2
printf %d "$count"
}
function countdir {
countdirhelper "$1" > /dev/null
}
答案2
以下 bash 脚本似乎适用于您的输入情况,只不过它./
为每个结果添加了前缀:
find . -type f |\
(
while read FN
do
echo "`dirname $FN`"
grep test "$FN" | wc -l
done
) |\
(
unset CTR
declare -A CTR
while read DN
do
read AA
while [ "$DN" != "." ]
do
PN=${CTR[$DN]}
[ "$PN" == "" ] && PN=0
CTR[$DN]=$((PN+AA))
DN="`dirname "$DN"`"
done
done
for DN in "${!CTR[@]}"
do
echo "$DN: ${CTR[$DN]}"
done
) | sort