2

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 '15 at 19:16
5

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 
12

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

$ echo "$var"
12

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␣) – Stéphane Chazelas Sep 9 '15 at 20:16
  • @StéphaneChazelas thanks, fortunately it didnt add any spaces in my case – JavaQuest Sep 9 '15 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.