36

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|
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Misha Moroshko
  • 166,356
  • 226
  • 505
  • 746
  • 4
    You tagged this with `printf`, so you pretty much knew the answer already. Why not check out how `printf` works? – Dan Fego Jan 24 '12 at 21:06

3 Answers3

57

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.

drrlvn
  • 8,189
  • 2
  • 43
  • 57
  • 2
    @Jaypal, I have no idea what just happened or why, but I'm sure it's not your fault :) – drrlvn Jan 24 '12 at 21:13
  • Spatz, @Jay was apologizing for [the edit he made to your answer](http://stackoverflow.com/posts/8994148/revisions) 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! – chown Dec 09 '12 at 03:43
5

You can use the - flag for left justification.

Example:

[jaypal:~] printf "%10s\n" $txt
     hello
[jaypal:~] printf "%-10s\n" $txt
hello
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
jaypal singh
  • 74,723
  • 23
  • 102
  • 147
2

Bash contains a printf builtin:

txt=1234567890
printf "%-10s\n" "$txt"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SiegeX
  • 135,741
  • 24
  • 144
  • 154