Bash Thousands Separator

The following bash script will take a number and convert it into a thousands separated equivalent.

This utility was written for my Backup script to allow the numbers produced by the du and df tools to be easily read within the logfiles etc. The default numbers reported by these tools were hard to compare without this modification.

Within my backup script this script is implemented as a function. Here it is presented as a standalone script.

Note that there are a couple of things that will make this script choke:

    Numbers too large, or too small.
    Numbers with decimal places.

Enjoy

#!/bin/sh

############################
#
# thousands-separator
#
# A BASH script to separate a number into it's equivalent with thousands separators
#
#    (C) 2006 Jim Pye - PyeNet Universal
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
#
# invocation: ./thousands-separator number-to-separate
#
# Change the variable THOU_SEP to the character to be used as the seperator
#
##############################


if [ -z "$1" ]; then
  echo "$0: Doh!, you forgot to give me a number to separate."
  exit 1
else
  declare -i NUM_ENT="$1"
fi

# Set the character to be used as the thousands separator
THOU_SEP=","

# Show the user the number that was entered on the command line
echo "Number Entered: $NUM_ENT"

# Declare Display Number as a string equal to number entered
declare +i DISP_NUM=$NUM_ENT

# Find the length of the Display Number variable
declare -i LGTH_DISP_NUM=${#DISP_NUM}

# Set up a variable to contain the part of the string being worked on and the
# thousands separator
SEP_NUM=""

# Loop thru cutting the number string into 3 character chunks and add the
# thousands separator
until [ $(($LGTH_DISP_NUM < 3)) = 1 ] ; do
  CURRENT_PART=${DISP_NUM:$(($LGTH_DISP_NUM - 3))}
  DISP_NUM=${DISP_NUM%$CURRENT_PART}
  SEP_NUM="$THOU_SEP$CURRENT_PART$SEP_NUM"
  LGTH_DISP_NUM=$(($LGTH_DISP_NUM - 3))
done

# Add the last chunk to the beginning of the number to be displayed
DISP_NUM=$DISP_NUM$SEP_NUM

# However if the number of digits in the number entered is divisible by 3
# it will have a leading thousands separator, this will remove it
DISP_NUM=${DISP_NUM#$THOU_SEP}

# Display the separated number
echo "     Separated: $DISP_NUM"

# YaHooooo
exit 0