Colorized grep — viewing the entire file with highlighted matches

前端 未结 21 2349
野趣味
野趣味 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:46

    The -z option for grep is also pretty slick!

    cat file1 | grep -z "pattern"
    
    0 讨论(0)
  • 2020-11-28 00:46

    It might seem like a dirty hack.

    grep "^\|highlight1\|highlight2\|highlight3" filename
    

    Which means - match the beginning of the line(^) or highlight1 or highlight2 or highlight3. As a result, you will get highlighted all highlight* pattern matches, even in the same line.

    0 讨论(0)
  • 2020-11-28 00:48

    To highlight patterns while viewing the whole file, h can do this.

    Plus it uses different colors for different patterns.

    cat FILE | h 'PAT1' 'PAT2' ...
    

    You can also pipe the output of h to less -R for better reading.

    To grep and use 1 color for each pattern, cxpgrep could be a good fit.

    0 讨论(0)
  • 2020-11-28 00:49

    Alternatively you can use The Silver Searcher and do

    ag <search> --passthrough
    
    0 讨论(0)
  • 2020-11-28 00:50

    You can also create an alias. Add this function in your .bashrc (or .bash_profile on osx)

    function grepe {
        grep --color -E "$1|$" $2
    }
    

    You can now use the alias like this: "ifconfig | grepe inet" or "grepe css index.html".

    (PS: don't forget to source ~/.bashrc to reload bashrc on current session)

    0 讨论(0)
  • 2020-11-28 00:51

    Here is a shell script that uses Awk's gsub function to replace the text you're searching for with the proper escape sequence to display it in bright red:

    #! /bin/bash
    awk -vstr=$1 'BEGIN{repltext=sprintf("%c[1;31;40m&%c[0m", 0x1B,0x1B);}{gsub(str,repltext); print}' $2
    

    Use it like so:

    $ ./cgrep pattern [file]
    

    Unfortunately, it doesn't have all the functionality of grep.

    For more information , you can refer to an article "So You Like Color" in Linux Journal

    0 讨论(0)
提交回复
热议问题