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

标签 bash perl awk sed grep

我每周运行一个 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

这是一个示例输出:

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

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

我想看到的是这个

imgur link

我已经尝试将当前输出通过管道传输到 | grep --color=auto \bRedundancy\w*\b(?<!Full)\|\bHealth\w*\b(?<!Ok)没有成功。如有任何帮助,我们将不胜感激。

最佳答案

在任何 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

enter image description here

你真的应该使用一个更健壮的字符串比较表达式,而不是当前松散的正则表达式:

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

关于bash - 如何为以 string1 开头但不以 string2 结尾的行着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48410744/

相关文章:

regex - sed 正则表达式提取字段并构建新的

c - 程序输出重定向的问题

linux - bash 脚本不为变量分配标志

objective-c - Cocoa 应用程序最简单的 Markdown 实现是什么?

bash - 用于计算数据文件中数字列表平均值的脚本

regex - 在两个标记字符串之间的字符串中查找/替换正则表达式模式

linux - 将错误重定向到一个文件,将标准输出重定向到另一个函数,然后再重定向到另一个文件

linux - 在 Linux 中将文件拆分为不相等的 block

perl - 如何在 Perl 中增加带有前导零的值?

perl - 如何在 Log4perl 中抑制输出到 stdout 和 stderr?