Reputation: 3854
I am new to shell scripting in linux. I want to be able to list the number of files in my directory, the number of directories in the directory and so fourth. I have decided to go upon this task by using
ls -l | cut -c1-1
So this way I can get the first character of every ls command and then based on what it is, keep a count of file type until all files are listed. So an example would be if I was in a folder with a bunch of files and did the cut command from above, it would display many "-" permissions indicating it was a file.
My question is this, based on the command above, how would I go through each ls line? If I enter the command from above in the shell, it simply displays all of them at once... I would like to go through each ls line.
Thanks!
Directory is called Test and contains
-rw-r--r-- 1 teddy user 31 27 Mar 10:07 test1.txt
drwx------ 1 teddy user 9 30 Jan 19:18 tooney
-rw-r--r-- 1 teddy user 31 27 Mar 10:07 test2.txt
drwx------ 1 teddy user 9 21 Mar 11:32 dirt
Upvotes: 0
Views: 110
Reputation: 54551
Using your method, you can calculate the totals using uniq
, for example:
$ ls -l | cut -c1-1 | sort | uniq -c
214 -
13 d
2 l
1 t
uniq -c
counts the number of consecutive occurrences of a line, and sort
just puts them into some sorted order so that the same types end up together.
If you want these results in variables, then something this would be easier:
dirs=0
files=0
for name in *
do
if [[ -d "$name" ]]
then
((dirs++))
elif [[ -f "$name" ]]
then
((files++))
# Possibly other things you want to count ...
fi
done
echo "Files: $files"
echo "Directories: $dirs"
Upvotes: 3
Reputation: 6651
Piping the command into more will keep it from scrolling off the screen.
ls -l | cut -c1-1 | more
Upvotes: 0
Reputation: 85795
How about using find
and wc
:
# Find all files in the current directory
$ find . -maxdepth 1 -type f | wc -l
# Find all directories in the current directory
$ find . -maxdepth 1 -type d | wc -l
The command wc
(word count) can be used to count the number of character, words and lines. Here wc -l
counts the number of lines output from the results of find
.
Upvotes: 4