Home > front end >  How do I add numbers from result?
How do I add numbers from result?

Time:12-22

I want to make a bash script that counts how many files there are in specific folders.

Example:

#!/usr/bin/env bash

sum=0

find /home/user/Downloads  | wc -l 
find /home/user/Documents  | wc -l 
find /home/user/videos | wc -l 

echo "files are $sum "

Downloads folder has 5 files, Documents has 10 files and videos has 10 files.

I want to add all files from above directories and print the number of files. echo "files are $sum "

Please I would like to use "only" find command, because my script delete some files. My goal is how many files I deleted.

CodePudding user response:

I'm not sure about this, but you can try this code.

#!/usr/bin/env bash

sum=0

downloads=$(find /home/user/Downloads | wc -l)
((sum  = downloads))
documents=$(find /home/user/Documents | wc -l)
((sum  = documents))
videos=$(find /home/user/videos | wc -l)
((sum  = videos))

echo "files are $sum "

CodePudding user response:

You can save the individual results and sum them as as per FS-GSW's answer.

That's what I would do in Java or C, but shell scripts have their own patterns. Whenever you find yourself with lots of variables or explicit looping, take a step back. That imperative style is not super idiomatic in shell scripts.

  • Can you pass multiple file names to the same command?
  • Can that loop become a pipe?

In this case, I would pass all three directories to a single find command. Then you only need to call wc -l once on the combined listing:

find /home/user/Downloads /home/user/Documents /home/user/videos | wc -l 

Or using tilde and brace expansion:

find ~user/{Downloads,Documents,videos} | wc -l

And if the list of files is getting long you could store it in an array:

files=(
    /home/user/Downloads
    /home/user/Documents
    /home/user/videos
)

find "${files[@]}" | wc -l

CodePudding user response:

Just use ..

find /home/user/ -type f | wc -l

.. to count the files inside the user directory recursively.

With tree you could also find/count (or whatever else you want to do) hidden files.

e.g. tree -a /home/user/ - for which the output would be: XXX directories, XXX files - which then wouldn't apply to your question though.

CodePudding user response:

Anything that's piping to wc -l isn't counting how many files you have, it's counting how many newlines are present, and so it'll fail if any of your file names contain newlines (a very real possibility given the specific directories you're searching). You could do this instead using GNU tools:

find \
     /home/user/Downloads \
     /home/user/Documents \
     /home/user/videos \
-print0 |
awk -v RS='\0' 'END{print NR}'
  •  Tags:  
  • bash
  • Related