Linux implements a decent version of grep and highlights the search term using colour. Whilst AIX  terminals can support colour (if your term session supports it) with escape codes I have not seen any way of making grep or egrep etc colourful.

On linux you simply add the parameter –color=auto such as
grep --color=auto SearchTerm  {files}

Well as I couldn’t find anything on google I decided to implement something. And this is what I came up with. However the one bug I didn’t manage to resolve was If searching case insensitively the highlighting will only find the correct case. As sed does not support case insensitively this is a problem to solve. If nawk or gawk is installed, they do support it with the -i parameter.


#!/bin/ksh
#************************************************************************
#                                                                       *
# Module Name : grepc.sh                                                *
# Author      : Dave Jarman                                             +
#                                                                       *
# Edit Record (most recent edit at top of list)                         *
# Date          By      CF      Comments                                *
# ---------     ---     ----    --------------------------------------- *
# 5-Apr-12      DCJ i           Use ampersand in sed search results as 
#                               matched string to better handle regular 
#                               expressions (thanks Zolo).
# 20-Sep-11     DCJ             New file                                *
#************************************************************************
#
# Executes grep but with the escape codes to colourise the output.
#
# Known Bugs:
#   If searching case insensitively the highlighting will only find the
# correct case. As sed does not support case insensitively this is a problem
# to solve. If nawk or gawk is installed, they do support it with the -i
# parameter.
#
# Other colours are available. Use the following lines.
# Blue          echo "s/$QRY/\033[1;34m$QRY\033[0m/g" > $TMP/$$.sed
# Light blue    echo "s/$QRY/\033[1;36m$QRY\033[0m/g" > $TMP/$$.sed
# Inverse blue  echo "s/$QRY/\033[44;37m$QRY\033[0m/g" > $TMP/$$.sed
# Red           echo "s/$QRY/\033[0;31m$QRY\033[0m/g" > $TMP/$$.sed
#************************************************************************
# Check for any options and save them
OPT=
while [[ $1 = [-+]?* ]]
do
  OPT="$OPT $1"
  shift
done
#
# Get the search string.
QRY=$1
shift
#
# Create a sed script to subsitiute for the appropriate colour.
# Show the search term in Blue
# echo "s/$QRY/\033[1;34m$QRY\033[0m/g" > $TMP/$$.sed
echo "s/$QRY/\033[1;34m&\033[0m/g" > $TMP/$$.sed
# echo /usr/bin/grep $OPT "$QRY" $* "|" sed -u -f $TMP/$$.sed
/usr/bin/grep $OPT "$QRY" $* | sed -f $TMP/$$.sed
#
# Clean up the tmp file                                                   *
rm $TMP/$$.sed
#
# Finish
exit 0