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?

3
  • 1
    Try grep "pattern" filename --color=always Commented Jul 23, 2014 at 10:23
  • 1
    try man grep, the answer is hard to miss even if you put in minimal effort Commented Jul 23, 2014 at 11:01
  • Please do not cross post: stackoverflow.com/questions/24907702/… Commented Jul 24, 2014 at 14:52

3 Answers 3

2
grep --color=always -e pattern -e '$'
8
  • @Stéphane Chazelas: This does not work for me, matched pattern is not colored. Any suggestion? My $TERM is vt100. Commented Jul 23, 2014 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. Commented Jul 23, 2014 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. Commented Jul 23, 2014 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. Commented Jul 23, 2014 at 10:55
  • @Gnouc, which version of grep is that? I've updated the answer. Commented Jul 23, 2014 at 11:42
1

Try this:

grep --color=always -e 'pattern\|$' file
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.