How to left justify text in Bash
Asked Answered
C

3

37

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|
Chavarria answered 24/1, 2012 at 21:2 Comment(1)
You tagged this with printf, so you pretty much knew the answer already. Why not check out how printf works?Fuge
B
59

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.

Bodkin answered 24/1, 2012 at 21:5 Comment(2)
@Jaypal, I have no idea what just happened or why, but I'm sure it's not your fault :)Bodkin
Spatz, @Jay was apologizing for the edit he made to your answer which deleted all the text except the printf line from your answer (I'm sure the edit was not made with malicious intent, I'm just trying to clear up the confusion, that is all). p.s., this answer helped me solve a problem I was having in one of my bash scripts, so thanks!Murdocca
R
5

You can use the - flag for left justification.

Example:

[jaypal:~] printf "%10s\n" $txt
     hello
[jaypal:~] printf "%-10s\n" $txt
hello
Roodepoortmaraisburg answered 24/1, 2012 at 21:6 Comment(1)
LOL, I ended up adding an example to spatz solution. Oh man this is getting crazy.Roodepoortmaraisburg
B
2

Bash contains a printf builtin:

txt=1234567890
printf "%-10s\n" "$txt"
Belton answered 24/1, 2012 at 21:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.