0

This question already has an answer here:

Given a filepath, I would like to find out how many lines there are and store them into a variable. For example:

/three_little_pigs.csv

straw
wood
bricks

In a file, I would like to have the number (or string 3) stored. Tried the following commands:

export P="three_little_pigs.csv"
NUM_LINES=(wc -l < "${P}")

but I'm always getting this error:

bash: house: line 12: syntax error near unexpected token `<'

marked as duplicate by muru, Sundeep, countermode, Rui F Ribeiro, Anthon Jul 24 '17 at 8:09

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.

  • It's not NUM_LINES=(wc -l < "${P}") but rather NUM_LINES=$(wc -l < "${P}") Also no need to capitalize the var name and just simply "$P" – Valentin Bajrami Jul 24 '17 at 7:20
3

To run a subshell use $(...) in bash. And you don't need to redirect the input, but simply name the input file. So ommit the <:

NUM_LINES=$(wc -l "$P")

Output:

3 three_little_pigs.csv

To get rid of the filename, one possibility (there are many others) is to use awk:

NUM_LINES=$(wc -l "$P" | awk '{print $1}')

EDIT 1:

OK, using redirection (<) will ommit the filename at all ... sorry ;)

NUM_LINES=$(wc -l < "$P")
  • 2
    Note that with some wc implementations, after NUM_LINES=$(wc -l < "$P"), $NUM_LINES will contain leading blanks. To discard them, a common trick is to use arithmetic expansion: NUM_LINES=$(($(wc -l "$P"))). That would also convert an empty output (like when the file can't be open) to 0. – Stéphane Chazelas Jul 24 '17 at 7:41
  • With some shells, like AT&T ksh or zsh (and assuming the default value of $IFS, one can also do wc -l < "$P" | read num_lines instead to get rid of those blanks. – Stéphane Chazelas Jul 24 '17 at 7:44
  • 1
    Another advantage of wc -l < "$P" over wc -l "$P" is that it would work for files whose name starts with -. With some wc implementations like GNU wc, it's also better than wc -l -- "$P" as it works for a file called -. – Stéphane Chazelas Jul 24 '17 at 7:48
  • Great! Didn't know about arithmetic expansion! Helpful!! Will continue reading about ... – ChristophS Jul 24 '17 at 7:49
  • @StéphaneChazelas But won't the num_lines shell variable be lost in the pipe-created subshell once read operation is complete? I mean, how does one get at the value in the $num_lines shell var. – user218374 Jul 24 '17 at 12:02

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