6

How can I fix the output width using printf?

This is an example script:

#!/bin/bash
OK=$(printf '\t%+50s\n' OK)
FAIL=$(printf '\t%+50s\n' FAIL)
for i in a aa aaa aaaa aaaaaa aaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa; do
        echo "$i $OK"
done

Output:

a                                                       OK
aa                                                      OK
aaa                                                     OK
aaaa                                                    OK
aaaaaa                                                  OK
aaaaaaaaaaaaaaaaa                                                  OK
aaaaaaaaaaaaaaaaaaaaaaaaaa                                               OK

I want something like:

a                                                       OK
aa                                                      OK
aaa                                                     OK
aaaa                                                    OK
aaaaaa                                                  OK
aaaaaaaaaaaaaaaaa                                       OK
aaaaaaaaaaaaaaaaaaaaaaaaaa                              OK
20

An easy way:

pipe your script to column -t

$ script.sh | column -t
a                           OK
aa                          OK
aaa                         OK
aaaa                        OK
aaaaaa                      OK
aaaaaaaaaaaaaaaaa           OK
aaaaaaaaaaaaaaaaaaaaaaaaaa  OK
18

Use the following printf approach to get the needed output:

#!/bin/bash
for i in a aa aaa aaaa aaaaaa aaaaaaaaaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaa; do
    printf '%-50sOK\n' $i 
done

Script output:

a                                                 OK
aa                                                OK
aaa                                               OK
aaaa                                              OK
aaaaaa                                            OK
aaaaaaaaaaaaaaaaa                                 OK
aaaaaaaaaaaaaaaaaaaaaaaaaa                        OK

  • OK - as static string is moved to the FORMAT (printf FORMAT [ARGUMENT])

  • $i - considered as printf argument

5

You didn't use a tool that formats output and, as $i gets wider, your output fails to align.

Replace

echo "$i $OK"

with

printf "%-50s %s\n" "$i" "$OK"

(replace "foo" by actual string).

where

  • 50s is a fixed width 50 char string,
  • - (minus) left-justify the string.
  • see man 3 printf for details about the format string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.