This question already has an answer here:

I want to output number of lines in text file.So I am using echo command but I am getting filename along with number of lines when I run the following code:

echo "$page" > t
total="$(wc -l t)"
echo "$total"

Output: 162 t

Note: Number of lines in file "t" are 162 only.

marked as duplicate by don_crissti, jimmij, mikeserv, garethTheRed, jasonwryan Dec 10 '14 at 6:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    This is a duplicate but here you go: wc -l < file – don_crissti Dec 10 '14 at 3:28

Whenever you use wc -l FILENAME, it would always print file name along with a number.

wc -l /etc/hosts
34 /etc/hosts

In order NOT to print the file name, you can use cat and pipe it's output to wc -l as follows:

cat /etc/hosts | wc -l

So, in your case, if you could change the total variable to total=$(cat t | wc -l), you should get only a number saved in the variable total.

On the other hand, you can use cut or awk in order to extract the number part from the wc -l t part as follows:

wc -l t | cut -d " " -f1

wc -l t | awk '{print $1}'

  • You don't need to call cat for this, just use shell redirection, as don_crissti commented above. – glenn jackman Dec 10 '14 at 4:13
  • @glennjackman - Noted. Thanks for your input. Also let me know if I am supposed to make that correction in the answer above. – Mandar Shinde Dec 10 '14 at 4:19

I don't know if there is a flag to prevent wc from printing the filename, but with cut you can just cut out your number:

wc -l filename  | cut -d' ' -f1
  • 1
    The funny thing is that symmetrical cut -d' ' -f1 filename | wc -l works too :) – jimmij Dec 10 '14 at 3:42
  • Yes, but this does something completely different. The reason why it works is just that you feed the content to wc through stdin so it can't print any filename (it doensn't know the filename), so cat filename | wc -l has exactly the same result – tkausl Dec 10 '14 at 3:45

Not the answer you're looking for? Browse other questions tagged or ask your own question.