如何为以string1开头但不以string2结尾的行着色

PCn*_*tMD 8 bash perl awk grep sed

我运行每周一次的crontab,它收集信息并创建一个日志文件.

我有一个脚本,我针对这个每周文件运行,只输出特定的状态行到我的显示器.

#!/bin/sh

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

# List the Site name, hardware group, Redundancy or Health status', and the site divider
grep -i 'Site\|^\*\*\|^Redundancy\|^Health\|^##' /home/user/hwinfo/$HW_FILE
echo "/home/user/hwinfo/"$HW_FILE
exit 0
Run Code Online (Sandbox Code Playgroud)

这是一个示例输出:

Accessing Site: site01
** FANS **
Redundancy Status : Full
** MEMORY **
Health : Ok
** CPUs **
Health : Ok
** POWER SUPPLIES **
Redundancy Status : Full
##########################################
Accessing Site: site02
** FANS **
Redundancy Status : Full
** MEMORY **
Health : Degraded
** CPUs **
Health : Ok
** POWER SUPPLIES **
Redundancy Status : Full
##########################################
Accessing Site: site03
** FANS **
Redundancy Status : Failed
** MEMORY **
Health : Ok
** CPUs **
Health : Ok
** POWER SUPPLIES **
Redundancy Status : Full
##########################################
/home/user/hwinfo/hwinfo_102217_034001.txt
Run Code Online (Sandbox Code Playgroud)

有没有办法cat/grep/sed/awk/perl /当前输出,以便任何以Redundancy或开头或者Health不以Full或者结尾的行Ok分别着色?

我想看到的是这个

imgur链接

我已经尝试将当前输出管道化| grep --color=auto \bRedundancy\w*\b(?<!Full)\|\bHealth\w*\b(?<!Ok)而没有成功.任何帮助将不胜感激.

Ed *_*ton 8

在任何UNIX机器上的任何shell中都有任何awk:

awk -v on="$(tput setaf 1)" -v off="$(tput sgr0)" '$1~/^(Health|Redundancy)$/ && $NF!~/^(Full|Ok)$/{$0 = on $0 off} 1'  file
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

你应该使用更强大的表达式与字符串比较,而不是当前松散的正则表达式:

awk -v on="$(tput setaf 1)" -v off="$(tput sgr0)" '
(($1=="Health") && ($NF!="Ok")) || (($1=="Redundancy") && ($NF!="Full")) { $0 = on $0 off }
1'  file
Run Code Online (Sandbox Code Playgroud)

  • 非常优雅! (2认同)

yst*_*sth 7

使用GNU grep:

| grep -P --color=auto '^Redundancy.*(?<!Full)$|^Health.*(?<!Ok)$|$'
Run Code Online (Sandbox Code Playgroud)

-P使用PCRE进行lookbehind(我不认为grep支持),|$使其输出所有行.您需要在行尾之前使用lookbehind.

  • 考虑在末尾添加`| $`而不是`-C` :) (3认同)