Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formatting bash in linux - printf align middle

Tags:

bash

printf

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
like image 301
andrej Avatar asked Dec 03 '13 21:12

andrej


2 Answers

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}`
like image 57
akrog Avatar answered Oct 02 '22 22:10

akrog


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 ""
like image 41
PasteBT Avatar answered Oct 02 '22 23:10

PasteBT