andrej
andrej

Reputation: 587

formatting bash in linux - printf align middle

This line of code:

printf 'ddd %-22s dddd \n' "eeeeeee"

Aligns to the left.

What could I use to align it to centre like this:

ddd      eeeeeee      dddd

Upvotes: 8

Views: 9179

Answers (3)

PasteBT
PasteBT

Reputation: 2198

printf not support it, but easy to implement it:

D="12"    # input string
BS=10     # buffer size
L=$(((BS-${#D})/2))
[ $L -lt 0 ] && L=0
printf "start %${L}s%s%${L}s end\n" "" $D ""

Upvotes: 2

akrog
akrog

Reputation: 326

A bit tricky ... but what about this? ;)

STR="eeeeeee"; printf 'ddd %11s%-11s dddd \n' `echo $STR | cut -c 1-$((${#STR}/2))` `echo $STR | cut -c $((${#STR}/2+1))-${#STR}`

Upvotes: 3

armandino
armandino

Reputation: 18528

Just add some tabs around it?

printf "ddd\t\teeeeee\t\tddd"

Upvotes: -1

Related Questions