Unexpected leading spaces while using wc -l command
Asked Answered
Q

2

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.

Quinate answered 28/8, 2015 at 7:21 Comment(3)
Related: #10238863 Does one of these machines run AIX?Kunzite
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.Lin
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.Phenolic
W
2

use

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

this matches also numbers with blanks in front.

Whitleywhitlock answered 28/8, 2015 at 7:29 Comment(3)
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.Quinate
@Quinate Think for better readability. But also think that this question will be off-topic.Whitleywhitlock
This answer simply repeats back to OP to follow the suggestion which OP made, and does not address the question which OP made.Wouldbe
W
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).

Wouldbe answered 28/8, 2015 at 8:29 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.