BASH – Center Align A File

Disclaimer

The instructions/steps/scripts/methods given below worked for me running CentOS. It may very well work for you on other linux distributions, Red Hat-like or otherwise. Please note that if you decide to use these instructions on your machine, you are doing so entirely at your very own discretion and that neither this site, sgowtham.com, nor its author is responsible for any/all damage – intellectual or otherwise.


What is BASH and SED?

BASH is a free software Unix shell written for the GNU Project. Its name is an acronym which stands for Bourne-again shell. The name is a pun on the name of the Bourne shell (sh), an early and important UNIX shell written by Stephen Bourne and distributed with Version 7 UNIX circa 1978, and the concept of being born again. BASH was created in 1987 by Brian Fox. In 1990 Chet Ramey became the primary maintainer. BASH is the default shell on most GNU/Linux systems as well as on Mac OS X and it can be run on most UNIX-like operating systems. It has also been ported to Microsoft Windows using the POSIX emulation provided by Cygwin, to MS-DOS by the DJGPP project and to Novell NetWare.

sed (Stream EDitor) refers to a UNIX utility which parses text files and implements a programming language which can apply textual transformations to such files. It reads input files line by line (sequentially), applying the operation which has been specified via the command line (or a sed script), and then outputs the line. It was developed from 1973 to 1974 as a UNIX utility by Lee E. McMahon of Bell Labs, and is available for most operating systems.


The Script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#! /bin/bash
 
# BASH script to center all text in the middle of 79-column width.
# Leading white spaces are insignificant and no trailing spaces appear at the end.
#
# Sun, 09 Apr 2006 08:47:20 -0400
 
if [ "$1" != "" ];
then
  echo
  echo "Center aligning the text in $1"
  export FILENAME=`echo $1 | awk -F '.' '{print $1}'`
  export EXTN=`echo $1 | awk -F '.' '{print $2}'`
  sed  -e :a -e 's/^.\{1,77\}$/ &/;ta' -e 's/\( *\)\1/\1/' $1 > $FILENAME_calign.$EXTN
  echo "Open $FILENAME_calign.$EXTN"
  echo
fi