I want to do a line count and get the number into a variable in a shell script. For eg.

 wc -l filename.dat

gives 221 filename.dat I want to grep '221' into a variable, which I could use later. Can this be done in a single statement ? I don't want to copy the output of wc -l into another file and then grep.

  • Word count or line count?
    – tachomi
    Sep 9, 2015 at 19:16

1 Answer 1


You can pass the filename to the STDIN of wc to get only the number of lines :

wc -l <filename.dat

To save it as a variable :

var="$(wc -l <filename.dat)"

Example :

$ wc -l foo.txt 
12 foo.txt

$ wc -l <foo.txt 

$ var="$(wc -l <foo.txt)"

$ echo "$var"

Note that as Stéphane Chazelas has pointed out, some wc variants might add spaces before and after the number of lines to get desired alignment.

  • Note that some wc implementations (typically the traditional ones) insert spaces before and after the number (to right-align on a 8 character column: ␣␣␣␣␣12␣) Sep 9, 2015 at 20:16
  • @StéphaneChazelas thanks, fortunately it didnt add any spaces in my case
    – JavaQuest
    Sep 9, 2015 at 20:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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