1

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 `<'
ChristophS
  • 565
  • 5
  • 13
bryan.blackbee
  • 113
  • 1
  • 1
  • 5

1 Answers1

8

To run a subshell use $(...) in bash. And you don't need to redirect the input, but simply name the input file. So omit 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 omit the filename at all ... sorry ;)

NUM_LINES=$(wc -l < "$P")
ChristophS
  • 565
  • 5
  • 13
  • 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 07: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 07: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 07:48
  • Great! Didn't know about arithmetic expansion! Helpful!! Will continue reading about ... – ChristophS Jul 24 '17 at 07: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. –  Jul 24 '17 at 12:02
  • @RakeshSharma, not in AT&T ksh or zsh that don't run that `read` in a subshell. See also the `lastpipe` option in `bash` (with restrictions) and `yash`. – Stéphane Chazelas Jul 24 '17 at 12:03