output a variable value using echo command

5,583

Solution 1

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
34

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}'

Solution 2

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
Share:
5,583

Related videos on Youtube

Abhinav Moudgil
Author by

Abhinav Moudgil

Updated on September 18, 2022

Comments

  • Abhinav Moudgil
    Abhinav Moudgil almost 2 years

    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.

    • don_crissti
      don_crissti over 9 years
      This is a duplicate but here you go: wc -l < file
  • jimmij
    jimmij over 9 years
    The funny thing is that symmetrical cut -d' ' -f1 filename | wc -l works too :)
  • tkausl
    tkausl over 9 years
    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
  • Angel Todorov
    Angel Todorov over 9 years
    You don't need to call cat for this, just use shell redirection, as don_crissti commented above.
  • Mandar Shinde
    Mandar Shinde over 9 years
    @glennjackman - Noted. Thanks for your input. Also let me know if I am supposed to make that correction in the answer above.