Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to left justify text in Bash

Given a text, $txt, how could I left justify it to a given width in Bash?

Example (width = 10):

If $txt=hello, I would like to print:

hello     |

If $txt=1234567890, I would like to print:

1234567890|
like image 837
Misha Moroshko Avatar asked Jan 24 '12 21:01

Misha Moroshko


3 Answers

You can use the printf command, like this:

printf "%-10s |\n" "$txt"

The %s means to interpret the argument as string, and the -10 tells it to left justify to width 10 (negative numbers mean left justify while positive numbers justify to the right). The \n is required to print a newline, since printf doesn't add one implicitly.

Note that man printf briefly describes this command, but the full format documentation can be found in the C function man page in man 3 printf.

like image 119
drrlvn Avatar answered Nov 03 '22 15:11

drrlvn


You can use the - flag for left justification.

Example:

[jaypal:~] printf "%10s\n" $txt
     hello
[jaypal:~] printf "%-10s\n" $txt
hello
like image 24
jaypal singh Avatar answered Nov 03 '22 16:11

jaypal singh


Bash contains a printf builtin:

txt=1234567890
printf "%-10s\n" "$txt"
like image 2
SiegeX Avatar answered Nov 03 '22 14:11

SiegeX