0

This is a simple script I use both at work, and for my home lab, and I'm looking to add color printing based on a few conditions.

#!/bin/bash

echo "Enter Search Values Below (regex or plain)"
printf "\n"
echo "Enter IP/Hostname: "
read ip
printf "\n"
echo "Enter Matching Keyword: "
read val1
printf "\n"
echo "Enter Another Keyword (null if none): "
read val2
printf "\n"
echo "Enter Another Keyword (null if none): "
read val3
printf "\n"
echo "Enter Log File: "
read log
awk '$4 ~ /'$ip'/{for(i=1;i<NF;i++){ if( $i ~ '/.*'('$val1'|'$val2'|'$val3')'/'){count[$i]++}} }END{ for(x in count){ print count[x],x}}' /var/log/$log | sed 's/'^[0-9].*[0-9]$'/& >/' | cut -d ':' -f1

Its a pretty simple one liner that I use to quickly count the number of times a keyword appears in a given log file. Here is sample execution and output:

sh-3.2# sh /scripts/log_search.sh 
Enter Search Values Below (regex or plain)

Enter IP/Hostname: 
Anonymous.local

Enter Matching Keyword: 
UDP

Enter Another Keyword (null if none): 
Stealth

Enter Another Keyword (null if none): 
netbios

Enter Log File: 
appfirewall.log
1154 > netbiosd
5572 > UDP
598 > Stealth

As you can See it returns the following Values and the number of times the given keywords appear keyword appears:

    1154 > netbiosd
    5572 > UDP
    598 > Stealth

I want to print the output in color based on the number value. For example, if the value appears more than 3000 times print in red, if 1000 < x < 3000 print in green, and anything less than 1000 print in white. How can I do this? I am not familiar color printing, I've found a few suggestions using tput and setaf, however I am not sure how to implement this with my one liner. Would this best be used with sed, or awk? If you could please provide an example, I would appreciate it.

higuaro
  • 15,730
  • 4
  • 36
  • 43
Bernard
  • 21
  • 6

1 Answers1

1

You can use these as your color variables

# Colors
txt_red="\033[31m"    # Red
txt_green="\033[32m"  # Green
txt_yellow="\033[33m" # Yellow
txt_blue="\033[36m"   # Blue
txt_reset="\033[0m"   # Reset the prompt back to the default color

And use echo -e

Here is an example from my dotfiles

if (($? > 0)); then
  echo -e "$txt_red""\n FAIL! There was a problem""$txt_reset"
    exit 1
else
  echo -e "$txt_green""\n Success! No errors\n""$txt_reset"
   exit 0
fi
AJ.
  • 1,248
  • 10
  • 27