Colorized grep — viewing the entire file with highlighted matches

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

    Here are some ways to do it:

    grep --color 'pattern\|$' file
    grep --color -E 'pattern|$' file
    egrep --color 'pattern|$' file
    

    The | symbol is the OR operator. Either escape it using \ or tell grep that the search text has to be interpreted as regular expressions by adding -E or using the egrep command instead of grep.

    The search text "pattern|$" is actually a trick, it will match lines that have pattern OR lines that have an end. Because all lines have an end, all lines are matched, but the end of a line isn't actually any characters, so it won't be colored.

提交回复
热议问题