I have had a look at all the other answers on stack overflow and have spent all day on this.
The first thing I am trying to do is count all the directories/subdirectories in a the specified directory, which ideally should be pretty simple. To begin with I ask the user to enter the directory name.
#Choosing directory
echo "Please type in directory cd: [directory name]"
read dirname
cd $dirname
echo "Entering directory"
This is working fine. Next there are two methods I have tried for finding the number of folders.
The directory I am testing has 6 directories/subdirectories in total within it and 3 files.
The first method is using 'find' and 'wc' on its own, however this outputs a string " 7" with spaces in front, I do not want to count the directory that we have selected. I also can't subtract one from this value if I set it as a variable as it is a string with spaces at the front.
direnum=`find . -type d | wc -l`
echo "$direnum"
(result = 7)(require result = 6)
The second method is using a 'for loop' along with 'find' and 'wc'. This method works fine, but is extremely slow when there is many files.
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"
(result = 6)(require result = 6)
I also tried both methods with the files, however it does not output the correct number. I have 3 files within the directory, the first method outputs 5 and the second method outputs the result 8 not sure how this works.
First method for file count
#Check number of files in directory
filenum=`find . -type f | wc -l`
echo "$filenum"
Again results in a string " 5" with lots of spaces in front.
(result = 5)(require result = 3)
Second method for file count
#Check number of files in directory
j=0
for f in `find . -type f`
do
j=`expr $j + 1`
done
(result = 8)(require result = 3)
If someone could put me on the right track it would be appreciated, I am not expecting a full solution, ideally I would like to figure it out on my own but I am probably doing something wrong.
使用最小深度
find . -mindepth 1 -type d | wc -l
Further to my comment:
declare -i direnum
direnum=$(find . -type d|wc -l)
(( direnum-- ))
echo "$direnum"
By the way, notice that I am using $( ... )
rather than back-ticks, Back-ticks are considered bad practice and obsolete.
The command "tree" counts files and folder from a relative position
tree /path
will give you the information. Do you need to use that info in other scripts?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.