9

Possible Duplicate:
bash echo number of lines of file given in a bash variable

Was wondering how you output the number of lines in a text file to screen and then store it in a variable. I have a file called stats.txt and when I run wc -l stats.txt it outputs 8 stats.txt

I tried doing x = wc -l stats.txt thinking it would store the number only and the rest is just for visual but it does not work :(

Thanks for the help

Community
  • 1
  • 1
Masterminder
  • 1,127
  • 7
  • 21
  • 31

2 Answers2

18

There are two POSIX standard syntax for doing this:

x=`cat stats.txt | wc -l`

or

x=$(cat stats.txt | wc -l)

They both run the program and replace the invocation in the script with the standard output of the command, in this case assigning it to the $x variable. However, be aware that both trim ending newlines (this is actually what you want here, but can be dangerous sometimes, when you expect a newline).

Also, the second case can be easily nested (example: $(cat $(ls | head -n 1) | wc -l)). You can also do it with the first case, but it is more complex:

`cat \`ls | head -n 1\` | wc -l`

There are also quotation issues. You can include these expressions inside double-quotes, but with the back-ticks, you must continue quoting inside the command, while using the parenthesis allows you to "start a new quoting" group:

"`echo \"My string\"`"
"$(echo "My string")"

Hope this helps =)

3

you may try:

x=`cat stats.txt | wc -l`

or (from the another.anon.coward's comment):

x=`wc -l < stats.txt`
none
  • 11,793
  • 9
  • 51
  • 87