Search code examples
linuxshellwc

File name printed twice when using wc


For printing number of lines in all ".txt" files of current folder, I am using following script:

for f in *.txt;
do l="$(wc -l "$f")";
echo "$f" has "$l" lines;
done 

But in output I am getting:

lol.txt has 2 lol.txt lines

Why is lol.txt printed twice (especially after 2)? I guess there is some sort of stream flush required, but I dont know how to achieve that in this case.So what changes should i make in the script to get the output as :

lol.txt has 2 lines

Solution

  • You can remove the filename with 'cut':

    for f in *.txt;
    do l="$(wc -l "$f" | cut -f1 -d' ')";
    echo "$f" has "$l" lines;
    done