Colorized grep — viewing the entire file with highlighted matches

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

提交回复
热议问题