0

How can I use grep command to display both matched and unmatched lines? Matched line should be in red and other lines should be in normal color.

Is there a grep option available to do that?

TPS
  • 2,481
Krishna M
  • 119

3 Answers3

2
grep --color=always -e pattern -e '$'
  • @Stéphane Chazelas: This does not work for me, matched pattern is not colored. Any suggestion? My $TERM is vt100. – cuonglm Jul 23 '14 at 10:38
  • 1
    @Gnouc, the vt100 terminal is monochrome. The first DEC terminal to support colors was VT241. But I doubt you're using a real VT100 terminal. In any case GNU grep doesn't use $TERM, it hardcodes the ANSI escape sequences (regardless of whether your terminal supports (or claims to support) them or not). If grep 'x\|$' works, so should grep -e X -e '^' though. Also, check your environment for GREP_COLOR or GREP_COLORS variables. – Stéphane Chazelas Jul 23 '14 at 10:50
  • @StéphaneChazelas: Suprising, grep 'x\|$' works but grep -e X -e '^', GREP_COLOR and GREP_COLORS both are null. I'm on Windows machine, using Secure Shell client to connect to my Linux Server. – cuonglm Jul 23 '14 at 10:54
  • @StéphaneChazelas: Oh, after testing, I see that grep -e X -e '^' works but grep -e '^' -e X like your answer does not. – cuonglm Jul 23 '14 at 10:55
  • @Gnouc, which version of grep is that? I've updated the answer. – Stéphane Chazelas Jul 23 '14 at 11:42
  • grep (GNU grep) 2.5.1 – cuonglm Jul 23 '14 at 11:46
  • @Gnouc, interestingly grep --color -e x -e '^' segfaults in OS/X (FreeBSD grep 2.5.1) but not with $, so I've updated the answer once again for better portability. – Stéphane Chazelas Jul 23 '14 at 12:09
  • @StéphaneChazelas: Do you have any ideal why grep --color -e x -e '^' cause a segfaults? – cuonglm Jul 24 '14 at 15:22
1

Try this:

grep --color=always -e 'pattern\|$' file
cuonglm
  • 153,898
0

If you want to match other lines to have some context, you can use the -A and -B options:

grep --color=always -A 9 -B 9 -e pattern

will give you 9 lines of context. If this is not sufficient, you can increase this value.

vinc17
  • 12,174