Colorized grep — viewing the entire file with highlighted matches

前端 未结 21 2488
野趣味
野趣味 2020-11-28 00:17

I find grep\'s --color=always flag to be tremendously useful. However, grep only prints lines with matches (unless you ask for context lines). Give

21条回答
  •  心在旅途
    2020-11-28 00:33

    Here's my approach, inspired by @kepkin's solution:

    # Adds ANSI colors to matched terms, similar to grep --color but without
    # filtering unmatched lines. Example:
    #   noisy_command | highlight ERROR INFO
    #
    # Each argument is passed into sed as a matching pattern and matches are
    # colored. Multiple arguments will use separate colors.
    #
    # Inspired by https://stackoverflow.com/a/25357856
    highlight() {
      # color cycles from 0-5, (shifted 31-36), i.e. r,g,y,b,m,c
      local color=0 patterns=()
      for term in "$@"; do
        patterns+=("$(printf 's|%s|\e[%sm\\0\e[0m|g' "${term//|/\\|}" "$(( color+31 ))")")
        color=$(( (color+1) % 6 ))
      done
      sed -f <(printf '%s\n' "${patterns[@]}")
    }
    

    This accepts multiple arguments (but doesn't let you customize the colors). Example:

    $ noisy_command | highlight ERROR WARN
    

提交回复
热议问题