How to get my one liner script to print color based on condition?

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.


Source: shell

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.