【问题标题】:How do you color lines that begin with string1 but do not end with string2如何为以 string1 开头但不以 string2 结尾的线条着色
【发布时间】:2018-07-02 19:20:02
【问题描述】:

我每周运行一个 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 / 当前输出,以便任何以RedundancyHealth 开头但不以FullOk 结尾的行,分别被着色?

我想看到的是这个

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

【问题讨论】:

    标签: bash perl awk sed grep


    【解决方案1】:

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

    您确实应该在字符串比较中使用更健壮的表达式,而不是当前松散的正则表达式:

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

    【讨论】:

    • 确实非常优雅!
    【解决方案2】:

    使用 GNU grep:

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

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

    【讨论】:

    • 考虑在末尾添加|$ 而不是-C :)
    • @PesaThe 聪明
    • 你应该提到它只适用于 GNU grep 并且根据维护者-P 的说法是“高度实验性的”(参见手册页),所以 YMMV 可以使用它。众所周知,它会通过核心转储退出。
    猜你喜欢
    • 1970-01-01
    • 2020-10-08
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多