Reputation: 45
I have a directory that contains only .txt files. I want to print the number of lines for every file. When I write cat file.txt | wc -l
the number of lines appears but when I want to make a script it's more complicated. I have this code:
for fis in `ls -R $1`
do
echo `cat $fis | wc -l`
done
I tried: wc -l $fis , with awk,grep and it doesn't work. It tells that:
cat: fis1: No such file or directory 0
How can I do to print the number of lines?
Upvotes: 0
Views: 71
Reputation: 20002
Not the problem here, but the echo command is more than needed: You can use
wc -l "${fis}"
What goes wrong?
You have a subdir called fis1
. Look to the output of ls
:
# ls -R fis1
fis1:
file1_in_fis1.txt
When you are parsing this output, your script will try
echo `cat fis1: | wc -l`
The cat
will tell you No such file or directory
and wc
counts 0
.
As @Barmar explained, ls
prints additional output you do not want.
Do not try to patch your attempt by | grep .txt
and if [ -f "${fis}"]; then ..
, these will fail with filename with spaces.txt
. So use find
or shopt
(and accept the answer of @Barmar or @Cyrus).
Upvotes: 0
Reputation: 780974
To find files recursively in subdirectories, use the find
command, not ls -R
, which is mainly intended for human reading.
find "$1" -type f -exec wc -l {} +
The problems with looping over the output of ls -R
are:
Upvotes: 1