I have the following folder structure:
A/B/C/D/E/00 A/B/C/D/E/01 . . A/B/C/D/E/23
Similarly,
M/N/O/P/Q/00 M/N/O/P/Q/01 . . M/N/O/P/Q/23
Now, each folder from 00 to 23 has many files inside, which I would like to count.
If I run this simple command:
ls /A/B/C/D/E/00 | wc -l I can get the count of files in each of these sub directories. I want to automate this or get it iteratively. Also, the final output I am looking at is a file that should look like this:
C E RESULT OF ls /A/B/C/D/E/00 | wc -l RESULT OF ls /A/B/C/D/E/01 | wc -l M Q RESULT OF ls /M/N/O/P/Q/00 | wc -l RESULT OF ls /M/N/O/P/Q/01 | wc -l
So, the output should look like this finally
C E 23 23 4 6 7 4 76 98 57 2 67 9 12 34 67 0 2 3 78 98 12 3 57 213 M Q 12 10 2 34 32 1 35 65 87 8 32 2 65 87 98 0 4 12 1 35 34 76 9 67
Please note, the values after the alphabets are the values of file counts of the 24 folders 00, 01 through 23.
Using the eval approach: I can hardcode and get the exact results. But, I wanted it in a way that would show me the data for the previous day. So this is what I did:
d=`date --date ="1 days ago" +%Y%m%d` month= `date +%Y%m` eval echo YZ $d '"$(ls "/A/B/YZ/$month/$d/"'{20150800..20150823})'| wc -l)"'
This works perfectly because in the given location there are files inside child directories 20150800,20150801..20150823. However when I try to generalize this like below, it shows no such file or directory:
eval echo YZ $d '"$(ls "/A/B/YZ/$month/$d/"'{"$d"00.."$d"23})'| wc -l)"'
Is there something I am missing in the above line?
Advertisement
Answer
A very safe way of counting files:
find . -mindepth 1 -exec printf x ; | wc -c
To not count recursively add -maxdepth 1
before -exec
.
Some other notes:
eval
is evil. Don’t use it. There is only one place I’ve ever seen where it’s appropriate, and that’s when usinggetopt
.- You should not parse the output of
ls
. - Use
$()
for command substitutions.