grep:为输出的不同部分着色

问题描述 投票:0回答:2

我正在尝试从 grep 输出一些文本并以不同的颜色突出显示。 这是我的数据:

    - name: the name
      displayName: "[JIRA REF] the name"
      description: JIRA REF
      exemptionCategory: waiver
      expiresOn: 2024-03-02T00:00:00Z
      policyDefinitionReferenceIds:
        - REFid
      scope: null

我需要每个键(名称、显示名称等)为蓝色,

JIRA REF
为红色

我已经设法将其隔离,因此关键是一种颜色,但是当我添加辅助条件时,它仅与该颜色匹配 例如

grep -A3 -B4 -P 2024-03-02 --color=auto file.txt \
| grep --color=auto -P \
'expiresOn|displayName|name|exemptionCategory|policyDefinitionReferenceIds|scope|description' \ 
-A3 -B4

将以红色输出每个键,但是当我添加时

grep -A3 -B4 -P 2024-03-02 --color=auto file.txt \
| grep --color=auto -P \
'expiresOn|displayName|name|exemptionCategory|policyDefinitionReferenceIds|scope|description' \ 
-A3 -B4 \
| GREP_COLOR='mt=01;31' grep --color=auto -P '.{0,0}JIRA.{0,4}' \
-A3 -B4

只有 JIRA REF 是彩色的

bash colors grep
2个回答
0
投票

有了

grep
,这看起来很复杂。

我会做什么:

#!/bin/bash

blue=$(tput setaf 4)
red=$(tput setaf 1)
reset=$(tput sgr0)

cat<<EOF | sed -e "s/.*/$blue&$reset/g" -e "s/\[JIRA REF\]/$red\[JIRA REF\]$blue/g"
    - name: the name
      displayName: "[JIRA REF] the name"
      description: JIRA REF
      exemptionCategory: waiver
      expiresOn: 2024-03-02T00:00:00Z
      policyDefinitionReferenceIds:
        - REFid
      scope: null
EOF

随时改进以满足您的需求。您拥有的不仅仅是一个入门脚本:)


0
投票

我会使用比 grep 更灵活的东西,例如sed:

sed -e 's/JIRA REF/\x1b[32mJIRA REF\x1b[0m/g' -e 's/\([a-zA-Z]*:\)/\x1b[31m\1\x1b[0m/g'  file.txt

它利用 VT100 兼容终端的 ANSI 颜色转义 (https://en.wikipedia.org/wiki/ANSI_escape_code),就像 grep 一样。

© www.soinside.com 2019 - 2024. All rights reserved.