How can I highlight lines of a file that begin with abc and DO NOT end with xyz?

I have a daily script that retrieves hardware stats from all of my RHEL servers every night and saves them to a yyyymmdd_daily.log file. I have other scripts that I run against these files to extract specific data (i.e. DriveArrrayStatus, HardwareStatus, DiskFreeSpace, etc.) for different tasks.

Example HardwareStatus script output:

#######################
Server: abc
** Fans **
Health: Ok
** Power Supplies **
Redundancy: Full
#######################
Server: bcd
** Fans **
Health: Partial
** Power Supplies **
Redundancy: Half
#######################
Server: cde
** Fans **
Health: Down
** Power Supplies **
Redundancy: None
#######################
etc... for 44 servers

Since there are seldom any failures, I would like to colorize the lines that show any kind of error when I run the script. I can select the lines to scrutinize using grep:

./HardwareStatus | grep '^Health\|^Redundancy\|$'

But from here I need to colorize ONLY the scrutinized lines that DO NOT end in their respective satisfactory responses:

./HardwareStatus | grep --color=auto -v 'Ok$\|Full$'

I've tried piping the line selection grep statement to a second grep or by using egrep, but it just drops any lines that do not have the satisfactory responses from the output of the script.

Any assistance would be greatly appreciated.


Solution 1:

You could use the colorama package in Python to write a simple filter (or perhaps include it in your HardwareStatus script, if that's written in Python)

#!/usr/bin/env python3

import fileinput
from colorama import init, Fore, Back, Style

init()
for line in fileinput.input():
    message = line.strip()
    if (("Health:" in message and "Ok" not in message) or
        ("Redundancy:" in message and "Full" not in message)):
        print(Back.RED + Fore.YELLOW + message + Style.RESET_ALL)
    else:
        print(message)

To use the above script, just pipe the output of HardwareStatus to it as you did with grep in your example above.

See the Colorama documentation for details.