Bash script for directory analysis and directory listing

I am working on a script that will parse any directory on unix and display the output: script.sh dir1 dir2 ... dirn

Required output: The xxx directory contains yy files and zz directories

#!/bin/bash echo 'Enter Dir names' read dirs for input_source in $dirs; do ls -ld|wc -l; echo # here goes a problem I am trying to figure out how to get this value printed by echo # together with dirs and files quantity 

Please inform.

I can’t figure out how to deal with the code. Please inform

+1
source share
2 answers

Note. Edited to take care of a new line in / dir file names.

It is better not to analyze the output of the ls .

To count files (no directories):

 find "$DIR" -maxdepth 1 -type f -exec echo -n . \; | wc -c 

To count dirs:

 find "$DIR" -maxdepth 1 -type d -exec echo -n . \; | wc -c 

Your complete script:

 #!/bin/bash echo 'Enter Dir names' read dirs for DIR in "$dirs"; do numFiles=$(find "$DIR" -maxdepth 1 -type f -exec echo -n . \; | wc -c) numDirs=$(find "$DIR" -maxdepth 1 -type d -exec echo -n . \; | wc -c) echo "Directory $DIR contains $numFiles files and $numDirs directories" done 
+3
source

in your code use the following: @where ls -ld is written

Getting directories

  ls -latr | sed -n '/^d/p' zdirlst | grep -v "\." 

receiving files:

  ls -latr | sed -n '/^-/p' zdirlst | grep -v "\." 

add wc -l to get the score and display according to reqd ...

hope this helps!

+1
source

Source: https://habr.com/ru/post/1484963/


All Articles