Bash 计算目录、子目录和文件
Bash counting directories, subdirectories and files
我查看了有关堆栈溢出的所有其他答案,并为此花了一整天时间。
我要做的第一件事是计算指定目录中的所有 directories/subdirectories,理想情况下这应该非常简单。首先,我要求用户输入目录名称。
#Choosing directory
echo "Please type in directory cd: [directory name]"
read dirname
cd $dirname
echo "Entering directory"
这工作正常。接下来我尝试了两种方法来查找文件夹的数量。
我正在测试的目录中总共有 6 个 directories/subdirectories 和 3 个文件。
第一种方法是单独使用'find'和'wc',但是这会输出一个前面有空格的字符串“7”,我这样做不想算我们选择的目录。如果我将它设置为一个变量,我也不能从这个值中减去一个,因为它是一个前面有空格的字符串。
direnum=`find . -type d | wc -l`
echo "$direnum"
(结果=7)(要求结果=6)
第二种方法 是使用 'for loop' 以及 'find' 和 'wc'。这个方法很好用,但是当文件很多的时候会很慢。
i=0
for d in `find . -type d`
do
i=`expr $i + 1`
done
#dont include the directory currently in
i=`expr $i - 1`
#output results
echo "Directories: $i"
(结果=6)(要求结果=6)
我也对文件尝试了这两种方法,但是它没有输出正确的数字。我在目录中有 3 个文件,第一种方法输出 5,第二种方法输出结果 8 不知道这是如何工作的。
第一种文件计数方法
#Check number of files in directory
filenum=`find . -type f | wc -l`
echo "$filenum"
再次得到前面有很多空格的字符串“5”。
(结果=5)(要求结果=3)
文件计数的第二种方法
#Check number of files in directory
j=0
for f in `find . -type f`
do
j=`expr $j + 1`
done
(结果=8)(要求结果=3)
如果有人能让我走上正轨,我将不胜感激,我不期待一个完整的解决方案,理想情况下我想自己解决,但我可能做错了什么.
使用mindepth
find . -mindepth 1 -type d | wc -l
进一步补充我的评论:
declare -i direnum
direnum=$(find . -type d|wc -l)
(( direnum-- ))
echo "$direnum"
顺便说一下,请注意我使用的是 $( ... )
而不是反引号,反引号被认为是不好的做法并且已经过时了。
命令"tree"从相对位置计算文件和文件夹
tree /path
会给你信息。
您需要在其他脚本中使用该信息吗?
我查看了有关堆栈溢出的所有其他答案,并为此花了一整天时间。
我要做的第一件事是计算指定目录中的所有 directories/subdirectories,理想情况下这应该非常简单。首先,我要求用户输入目录名称。
#Choosing directory
echo "Please type in directory cd: [directory name]"
read dirname
cd $dirname
echo "Entering directory"
这工作正常。接下来我尝试了两种方法来查找文件夹的数量。
我正在测试的目录中总共有 6 个 directories/subdirectories 和 3 个文件。
第一种方法是单独使用'find'和'wc',但是这会输出一个前面有空格的字符串“7”,我这样做不想算我们选择的目录。如果我将它设置为一个变量,我也不能从这个值中减去一个,因为它是一个前面有空格的字符串。
direnum=`find . -type d | wc -l`
echo "$direnum"
(结果=7)(要求结果=6)
第二种方法 是使用 'for loop' 以及 'find' 和 'wc'。这个方法很好用,但是当文件很多的时候会很慢。
i=0
for d in `find . -type d`
do
i=`expr $i + 1`
done
#dont include the directory currently in
i=`expr $i - 1`
#output results
echo "Directories: $i"
(结果=6)(要求结果=6)
我也对文件尝试了这两种方法,但是它没有输出正确的数字。我在目录中有 3 个文件,第一种方法输出 5,第二种方法输出结果 8 不知道这是如何工作的。
第一种文件计数方法
#Check number of files in directory
filenum=`find . -type f | wc -l`
echo "$filenum"
再次得到前面有很多空格的字符串“5”。
(结果=5)(要求结果=3)
文件计数的第二种方法
#Check number of files in directory
j=0
for f in `find . -type f`
do
j=`expr $j + 1`
done
(结果=8)(要求结果=3)
如果有人能让我走上正轨,我将不胜感激,我不期待一个完整的解决方案,理想情况下我想自己解决,但我可能做错了什么.
使用mindepth
find . -mindepth 1 -type d | wc -l
进一步补充我的评论:
declare -i direnum
direnum=$(find . -type d|wc -l)
(( direnum-- ))
echo "$direnum"
顺便说一下,请注意我使用的是 $( ... )
而不是反引号,反引号被认为是不好的做法并且已经过时了。
命令"tree"从相对位置计算文件和文件夹
tree /path
会给你信息。 您需要在其他脚本中使用该信息吗?