Shell – Align text to center with padding on both sides

awkshell-scripttext processing

Is there an easy way to align text to the center with padding on both sides, with the column width being the longest line from the input?

For example, this:

aaa
bbbb
c
ddddd
ee

will turn into this (the dots represent spaces):

.aaa.
bbbb.
..c..
ddddd
.ee..

Any tool is fine. Be it sed or awk or a bunch of coreutils tools.

Edit: I think some of you misunderstood the output. The output is padded with spaces, not dots. I've used dots here just to make it more clear.

Best Answer

I'd use vim. From normal mode:

:%center 5

...will act on every line in the file (that's the meaning of the % in this case), centring it to five characters (referred to as columns in the vim documentation). This will act exactly as you describe. To get the longest line in a file (for use in the center command), use wc -L file.txt; or within vim:

:! wc -L %

Unfortunately this isn't available in vanilla vi, but since this is tagged 'linux' it's likely that you have vim in your repositories at least.

You can also do this in one line with:

vim file.txt -c '%center 5' -c 'wq' &> /dev/null

...but I'm sure that's not the fastest way of doing things.

Related Question