Shell – Extra space with counted line number

shellstringwc

I count the number of lines of my file with this command on OSX:

nl=$(wc -l < ~/myfile.txt)

Say, nl turns out to be 100. Now, I wish to use the result nl in another command, but weirdly,

echo 1-$nl

gives me 1- 100 instead of 1-100.

Demo

cv me$ nl=$(wc -l < ~/Desktop/cap.xlsx)
cv me$ echo $nl
104
cv me$ echo 1-$nl
1- 104

enter image description here

enter image description here

Why does this happen? How may I get 1-100?

Best Answer

As POSIX defined, the output of wc shall contain an entry for each input file of the form:

"%d %d %d %s\n", <newlines>, <words>, <bytes>, <file>

But the output file format pseudo printf() string differs from the System V version of wc:

"%7d%7d%7d %s\n"

POSIX didn't require leading spaces to be added, so it's free for implementation to do what it want. There are different implementations of wc, at least with OSX and wc from heirloom tools chest, it added leading spaces to output.

$ /usr/5bin/wc -l /tmp/file
      3  /tmp/file

GNU wc also add leading spaces when reading from standard in and without any options:

$ cat file | wc
  5       5      65

To remove all leading spaces, in POSIX shell:

set -f
set -- $nl
nl=$1
set +f

Note that this approach assume that variable only contain leading or trailing spaces, no spaces in the middle, like a b.

Related Question