我需要循环编写脚本,该脚本将对文件和目录的数量进行计数,并指示哪个功能和数量。像这样:文件比目录多10个。 我正在尝试类似的操作,但是它只显示文件和目录,我不知道如何指示更大的文件等。谢谢您的帮助
shopt -s dotglob
count=0
for dir in *; do
test -d "$dir" || continue
test . = "$dir" && continue
test .. = "$dir" && continue
((count++))
done
echo $count
for -f in *; do
"$fname"
done
答案 0 :(得分:0)
这是我前一段时间使用的递归目录遍历。添加了对目录和文件的计数:
#!/bin/sh
# recursive directory walk
loop() {
for i in *
do
if [ -d "$i" ]
then
dir=$((dir+1))
cd "$i"
loop
else
file=$((file+1))
fi
done
cd ..
}
loop
echo dirs: $dir, files: $file
将其粘贴到script.sh
并运行:
$ sh script.sh
dirs: 1, files: 11
答案 1 :(得分:0)
使用可以使用find
获取目录中files/folders的数量。使用wc -l
对找到的路径数进行计数,可用于计算/显示结果;
#!/bin/bash
# Path to search
search="/Users/me/Desktop"
# Get number of files
no_files=$(find "$search" -type f | wc -l )
# Number of folders
no_folders=$(find "$search" -type d | wc -l )
echo "Files: ${no_files}"
echo "Folders: ${no_folders}"
# Caculate dif
diff=$((no_files - $no_folders))
# Check if there are more folders or files
if [ "$diff" -gt 0 ]; then
echo "There are $diff more files then folders!"
else
diff=$((diff * -1 ) # Invert negative number to positive (-10 -> 10)
echo "There are $diff more folders then files!"
fi;
文件:13
文件夹:2
然后是文件夹,还有11个文件!
答案 2 :(得分:0)
您可以使用find命令使事情变得更简单。
以下命令将列出给定路径中的所有文件:
find "path" -mindepth 1 -maxdepth 1 -type f
并使用-type d
将获得目录。
在wc -l
中进行管道查找将为您提供编号,而不是实际的文件和目录名称,因此:
root="${1:-.}"
files=$( find "$root" -mindepth 1 -maxdepth 1 -type f | wc -l)
dirs=$( find "$root" -mindepth 1 -maxdepth 1 -type d | wc -l)
if [ $files -gt $dirs ]; then
echo "there are $((files - dirs)) more files"
elif [ $files -lt $dirs ]; then
echo "there are $((dirs - files)) more dirs"
else
echo "there are the same"
fi