Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop through a directory and get wc of every txt file?

Tags:

linux

bash

shell

sh

The shell is sh.

I have been using a for loop:

for F in *.txt
do
echo `wc -w $F`
done

This has been returning the number of words and the name of the file. I don't understand why it keeps returning the name of the file; it looks like it should only return the number of words in the file.

like image 301
ENS Avatar asked Oct 29 '25 17:10

ENS


1 Answers

This is the default behavior of wc, it shows the filename after the count.

If you just want the count, pass the filename via STDIN:

wc -w <filename

Also, without iterating over the files using for, you could just use globbing for getting the filenames at once, wc takes multiple arguments so there would not be a problem:

wc -w *.txt

In this case, to get rid of the filenames, use some text-processing:

wc -w *.txt | awk '{print $1}'

This should be faster than the fora approach you have already.

like image 195
heemayl Avatar answered Oct 31 '25 07:10

heemayl