nicoulaj / rainbow

:rainbow: Colorize commands output or STDIN using patterns.
GNU General Public License v3.0
250 stars 35 forks source link

Request: Partial coloring of matches #118

Open AndydeCleyre opened 4 years ago

AndydeCleyre commented 4 years ago

Example log output:

[2019-12-09T12:06:34-0500] [ALPM] running '30-systemd-update.hook'...
[2019-12-09T12:06:34-0500] [ALPM] running 'detect-old-perl-modules.hook'...
[2019-12-09T12:06:34-0500] [ALPM] running 'gtk-update-icon-cache.hook'...
[2019-12-09T12:06:35-0500] [ALPM] running 'update-desktop-database.hook'...

Example goal: colorize the <month>-<day> part of each line, if present.

Current best possibility, as far as I know:

rainbow --blue '\d\d-\d\dT'

This also colorizes the T, which is useful for matching, but it would be nice to optionally specify a subset of each match to apply the color to.

One possible approach: add up to one --groups GROUPS switch after each style-pattern switch, to limit the styling to specific parenthesized groups in the match:

rainbow --blue '(\d\d-\d\d)T' --groups 1
rainbow --blue '(\d\d)-(\d\d)T' --groups 1,2
rainbow --blue '(\d\d)-(\d\d)T' --groups 1-2  # unnecessary, just for bonus points

If it turns out to be better or simpler to work on exclusion instead, that's just as effective:

rainbow --blue '\d\d-\d\d(T)' --exclude 1
rainbow --blue '\d\d(-)\d\d(T)' --exclude 1,2
rainbow --blue '\d\d(-)\d\d(T)' --exclude 1-2  # unnecessary, just for bonus points
  1. Am I missing a way to accomplish this sort of thing already?
  2. If not, might this be a good feature for the project?
nicoulaj commented 4 years ago

I think what you are looking for is "positive lookbehind". I did not test it but it should look something like:

(?<=\d{4}-)\d{2}-\d{2}
AndydeCleyre commented 4 years ago

I didn't realize that was supported here, thanks, I'll play with this. I also found this particular example goal can be achieved with

rainbow --blue-after '^\[\d{4}-' --reset-all-before 'T\d\d:\d\d:\d\d'

EDIT: Yes, thank you, your suggestion indeed works. I still like the --groups syntax idea, but it does seem unnecessary now. Please close this if you like. Is the specific regex syntax supported mentioned anywhere?

AndydeCleyre commented 4 years ago

Adding here, maybe just for documentation, that positive lookahead can also be used, as here in the --bold switch:

when () {  # <pkgname-filter>
    ((( $+commands[rainbow] )) &&
        grep -aEi "ed [^ ]*$1" /var/log/pacman.log \
        | rainbow \
            --blue '(?<=^\[\d{4}-)\d{2}-\d{2}' \
            --blue reinstalled \
            --green installed \
            --yellow upgraded \
            --red removed \
            --bold '[^ \(]+(?=\)$)' \
            --cyan $1
    ) ||
        grep -aEi "ed [^ ]*$1" /var/log/pacman.log
}

image