Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you colorize specific lines that are grepped from a file?

Tags:

bash

sed

awk

perl

I run a weekly CRONTAB that collects hardware info from 40+ remote servers and creates a weekly log file on our report server at the home office. I have a script that I run against this weekly file to output only specific status lines to my display.

#!/bin/sh

# store newest filename to variable
DD_FILE="$(ls -t /home/user/ddinfo/|head -1)"

# List the site name, disk ID (virtual & physical), Status and State of each ID, Failure Prediction for each physical disk, and the site divider
grep -w 'Site\|^ID\|^State\|^Status\|^Failure Predicted\|^##' /home/user/ddinfo/$DD_FILE
echo "/home/user/ddinfo/"$DD_FILE
exit 0

This is a sample output:

Accessing Site: site01
ID                            : 0
Status                        : Ok
State                         : Ready
ID                              : 0:0:0
Status                          : Ok
State                           : Online
Failure Predicted               : No
ID                              : 0:0:1
Status                          : Ok
State                           : Online
Failure Predicted               : No
################################################
Accessing Site: site02
ID                            : 0
Status                        : Ok
State                         : Ready
ID                              : 0:0:0
Status                          : Non-Critical
State                           : Online
Failure Predicted               : Yes
ID                              : 0:0:1
Status                          : Ok
State                           : Online
Failure Predicted               : No
################################################

Is there a way to cat / grep / sed / awk / perl / this output so that any lines that end with either Critical or Yes, get colorized?

like image 729
PCnetMD Avatar asked Nov 29 '22 22:11

PCnetMD


2 Answers

With GNU grep:

grep --color -E ".*Yes$|.*Critical$|$" file
like image 119
Cyrus Avatar answered Dec 04 '22 03:12

Cyrus


You could try ack, a very nice alternative to grep:

% ack '(Critical|Yes)$' file
# Or to colorize the whole line:
% ack '(.*(Critical|Yes))$' file

See Beyond grep

Or if you want to see all lines and only colorize specific ones:

use Term::ANSIColor qw/ colored /;
while (<$fh>) {
    s/(.*)(Critical|Yes)$/colored(["yellow bold"], $1.$2)/e;
    print;
}
like image 24
tinita Avatar answered Dec 04 '22 04:12

tinita