Reputation: 319
I'm new into shell and stuff, and i encountered a problem. I have to count how many lines have the files in a directory together
with this i count the line length of each file in for $i:
find $i -maxdepth 1 -type f -exec wc -l {} \; | tr -s " " | cut -d " " -f 2
i is a list of directories and the upper code is in a foreach cycle the output of this are number how many lines has the actual file, now i just have to sum them
But i need to sum the lenght for all files in the directory
tried to add the line to some variable:
@ variable = (`find $i...`)
but it gave me badly formed number error.
anybody has an idea how to solve this? im desperate, trying to do it for whole day,
Upvotes: 0
Views: 905
Reputation: 263557
First of all, the wc
command will add up the line counts for you, so this:
wc -l $i/* | tail -n 1
will very nearly do what you want; the differences are that it doesn't eliminate things other than plain files, and it doesn't count "hidden" files whose names start with .
. This:
wc -l `find $i -maxdepth 1 -type f -print` /dev/null | tail -n 1
should do what you want. (The addition of /dev/null
is a trick to handle the case where there are no files in the directory.) The output is going to be something like
210 total
(with leading spaces); you can capture the number using awk
:
wc -l `find $i -maxdepth 1 -type f -print` /dev/null | tail -n 1 | awk '{print $1}'
If you want to use the shell to add up the numbers yourself, this should do it:
@ total = 0
foreach file ( `find $i -maxdepth 1 -type f` )
@ total += `wc -l < $file`
end
though for very large directories you might run into a limit on the length of a command line.
Finally, I feel obligated to let you know that csh and tcsh are not good shells for programming. Their syntax is highly irregular. I've been using them for decades, and I still have to resort to trial and error to find out whether a particular construct is going to work. I strongly suggest learning sh
and/or bash
instead. See this article.
Upvotes: 1