FlyingAura
FlyingAura

Reputation: 1601

Remove multiple spaces in ls -l output

I need to display the filesize and the filename. Like this:

4.0K Desktop

I'm extracting these two fields using cut from the ls -l output:

ls -lhS | cut -d' ' -f5,9

Due to multiple spaces in the ls -l output, I'm getting a few erroneous outputs, like:

4.0K 19:54
4.0K 19:55
 6
 18:39
 31
 25

How should I fix this?

I need to accomplish this task using pipes only and no bash scripting ( output could be multiple pipes ) and preferably no sed, awk.

If no alternative to sed or awk is available- use of sed is OK.

Upvotes: 1

Views: 790

Answers (3)

James Brown
James Brown

Reputation: 37394

Or you could just submit to awk:

$ ls -lhS | awk '$0=$5 OFS $9'

ie. replace whole record $0 with fields $5 and $9 separated by output field separator OFS.

Upvotes: 0

Inian
Inian

Reputation: 85530

You can avoid parsing ls output and use the stat command which comes as part of GNU coreutils in bash for detailed file information.

 # -c  --format=FORMAT
 #         use the specified FORMAT instead of the default; output a newline after each use of FORMAT

 # %n     File name
 # %s     Total size, in bytes

 stat -c '%s %n' *

Upvotes: 2

Selvaram G
Selvaram G

Reputation: 748

You can use translate character command before using cut.

ls -lhS | tr -s ' ' | cut -d' ' -f 5,9

Upvotes: 1

Related Questions