7

I am trying to execute the below command - but the output has some leading space introduced.

ls -lrt | wc -l
     29
echo $SHELL
/bin/bash

When I run the same command on a different machine,the output is as expected.

ls -lrt | wc -l
183
echo $SHELL
/bin/bash

The leading spaces is causing my perl validation to fail

unless ( $phCountRet->{COUNT} =~ /^\d+$/ ){
...
}

I can opt to trim the leading white spaces and then do the validation,but it wont be a clean solution.

Any pointer as to what might be causing this will be a great help.

Soumya
  • 885
  • 3
  • 14
  • 29
  • Related: http://stackoverflow.com/questions/10238363/how-to-get-wc-l-to-print-just-the-number-of-lines-without-file-name Does one of these machines run AIX? – reinierpost Aug 28 '15 at 08:09
  • Why do you think trimming the whitespace is not clean? `ls | wc -l | sed -e 's/^ *//'` doesn't seem any less clean than `ls -lrt | wc -l`, but you could just do the equivalent of `perl -E 'say length glob "*"'` and not shell out to wc at all. – William Pursell Aug 28 '15 at 23:01
  • 1
    When you run `wc` with multiple file names, it aligns and right-justifies the numbers so they're more legible (at least some implementations do). The output is meant for to be human-readable than machine-readable. You just have to allow for variations in whitespace in the output. – Keith Thompson Aug 29 '15 at 00:24

2 Answers2

2

use

unless ( $phCountRet->{COUNT} =~ /^\s*\d+$/ ){

this matches also numbers with blanks in front.

Jens
  • 67,715
  • 15
  • 98
  • 113
  • Thanks Jens. Yes, I can definitely modify the regex to suit this case.But,I would still be more interested to know why the leading spaces are introduced. – Soumya Aug 28 '15 at 07:36
  • @Soumya Think for better readability. But also think that this question will be off-topic. – Jens Aug 28 '15 at 07:38
  • This answer simply repeats back to OP to follow the suggestion which OP made, and does not address the question which OP made. – Thomas Dickey Aug 28 '15 at 20:29
2

As I noted in WC on OSX - Return includes spaces, this is an implementation detail, which is not explicit in the POSIX standard (so it depends on the implementer's preference to align columns—or not).

Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105