in bash, if I want to execute a command and only display output lines that matches a certain pattern, I can pipe it to grep, like

file testfile



$ cat testfile | grep 'hello'
hello #this will be highlightd

this will highlight the search match and display the entire line it falls on. I can use -A and -B to display lines before and after that line. My question is is it possible to execute the command and display all output as normal, but to highlight the search matches like grep would? so my ouput would be

hello #highlighted

Add option -z to your GNU grep command:

cat testfile | grep --color=always -z 'hello'

or shorter

grep --color=always -z 'hello' testfile
  • 1
    This is a very crude hack.   It has the effect of treating the entire file as a single line.   Therefore, (1) if the file is very large, there may be a possibility of running out of memory, and (2) if the file doesn’t contain the pattern at all, then nothing will be output. – G-Man Feb 6 '17 at 4:41
  • What version of grep is this supported on? On grep 2.5.4, -z doesn't seem available... – Alex Jun 29 '17 at 22:29
  • @Alex: I used GNU grep version 2.6.3. – Cyrus Jun 30 '17 at 2:37
  • 1
    @G-Man: more resource-saving: grep --color "hello\|$" file – Cyrus Feb 9 '18 at 17:06
  • @Cyrus: Yes, that’s a better answer. Unfortunately, it is essentially equivalent to bot779’s answer to this question, and almost identical to the accepted answers (1 and 2) to the questions I linked to. – G-Man Feb 9 '18 at 18:10

To use a Color GREP to only highlight matched patterns but not otherwise change the output:

grep --color=always -e "^" -e "hello" testfile

The first pattern will match all lines (all lines will be printed) the second pattern (and any following patterns) cause the matched text to be highlighted in color.

Since the first pattern matches all lines but does not match on a printable character, it does not add any color highlighting so it doesn't compete/interfere with the readability of the highlighted text.

  • Works with kubectl kubectl apply -k . | grep --color=always -e "^" -e "configured" in zsh – Michael Cole Jun 3 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.