I have a directory, inside it multiple directories which contains many type of files.
I want to find *.jpg
files then to get the count and total size of all individual one.
I know I have to use find wc -l
and du -ch
but I don't know how to combine them in a single script or in a single command.
find . -type f name "*.jpg" -exec
- not sure how to connect all the three
CodePudding user response:
Supposing your starting folder is .
, this will give you all files and the total size:
find . -type f -name '*.jpg' -exec du -ch {}
The
at the end executes du -ch
on all files at once - rather than per file, allowing you the get the frand total.
If you want to know only the total, add | tail -n 1
at the end.
Fair warning: this in fact executes
du -ch file1 file2 file3 ...
Which may break for very many files. To check how many:
$ getconf ARG_MAX
2097152
That's what is configured on my system.
This doesn't give you the number of files though. You'll need to catch the output of find
and use it twice.
The last line is the total, so we'll use all but the last line to get the number of files, and the last one for the total:
OUT=$(find . -type f -name '*.jpg' -exec du -ch {} )
N=$(echo "$OUT" | head -n -1 | wc -l)
SIZE=$(echo "$OUT" | tail -n 1)
echo "Number of files: $N"
echo $SIZE
Which for me gives:
Number of files: 143
584K total
CodePudding user response:
If you would like to get the amount of lines and size of each individual .jpg
file in a directory, you can try this script.
#!/usr/bin/env bash
#Create variable to store the totals of .jpg file found and their line count.
Files=$(wc -l *.jpg | tail -1 | awk '{print "Total Files: "$1}')
sizes=$(du -ch *.jpg | tail -1 | awk '{print "Total Size: " $1}')
#Create temporary directories
size="tempsizefile.txt"
line="templinefile.txt"
#Begin a loop to display each file seperately showing line count and size
for j in *.jpg; do
du -ch $j |awk 'NR==1{print $1}' > "$size" #Size used
wc -l $j > "$line" #Total lines in each file and filename
paste "$size" "$line"
rm -f "$size" "$line" #Paste then remove the temp files
done
echo "Size Lines Filename"
echo
#Optional if the individual display is not needed.
echo "$Files"
echo "$sizes"
Output
4.0K 1 a90.jpg
4.0K 1 a91.jpg
4.0K 1 a92.jpg
4.0K 1 a93.jpg
4.0K 1 a94.jpg
4.0K 1 a95.jpg
4.0K 1 a96.jpg
4.0K 1 a97.jpg
4.0K 2 a98.jpg
4.0K 1 a99.jpg
4.0K 1 a9.jpg
Size Lines Filename
Total Files: 100
Total Size: 400K