How to align multiple lines with echo or print

text processing

I have a script which check the mounted file system against the entry listed under fstab, the issue what I am facing here is to keep the output align.

Below is the script output:

/  is mounted OK
/boot  is mounted OK
/was8  is mounted OK
/was8/slogs  is mounted OK
/was8/cluster  is mounted OK
/was8/working  is mounted OK
/was8/app  is mounted OK
/was8/tools  is mounted OK
/was8/plugin  is mounted OK
/was8/coreproduct  is mounted OK
...

I want to keep these line aligned so it should look like this:

/  is mounted                       OK
/boot  is mounted                   OK
/was8  is mounted                   OK
/was8/slogs  is mounted             OK
/was8/cluster  is mounted           OK
/was8/working  is mounted           OK
/was8/app  is mounted               OK
/was8/tools  is mounted             OK
/was8/plugin  is mounted            OK
/was8/coreproduct  is mounted       OK
...

I have tried column and xargs unable to get the desire result. Can someone help me with this.

Best Answer

In general, when you're doing the printing, you can set the width in the format string to printf. %-20s would print a string on a field 20 characters(*) wide, unless it overflows. %-20.20s would make it 20 characters and drop any overflowing part.

(* Though e.g. Bash's printf actually counts bytes. The difference can be seen with characters like รค in UTF-8.)

So, e.g.

printf "%-40s %s\n" "$mountpoint  is mounted" "$status"

would make the first part (at least) 40 characters wide:

/was8/coreproduct  is mounted            OK
...

Or, if you need to post-process an input like that, you could use Perl or awk:

perl -pe 's/(.*) +(\S+)$/ sprintf "%-40s %s", $1, $2 /e'  < file

awk '{s=$NF; sub(/ *[^ ]+ *$/, "", $0); printf "%-40s %s\n", $0, s}'  < file

Both basically separate the last non-whitespace string, and then print the two parts with the first on a fixed-width field.


Or, if you don't care about keeping the separation between the fields exactly as they were, a simpler solution commented by @JJoao would be:

awk '{s=$NF; NF-- ; printf "%-40s %s\n", $0, s}' < file

That produces the below output. Note that the two-space blank before is mounted is collapsed to one. This happens since awk rebuilds the whole $0 when NF or any of the fields are modified.

/was8/coreproduct is mounted             OK
Related Question