Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Convince grep to output all lines, not just those with matches

Say I have the following file:
$ cat test

test line 1
test line 2
line without the search word
another line without it
test line 3 with two test words
test line 4

By default, grep returns each line that contains the search term:

$ grep test test

test line 1
test line 2
test line 3 with two test words
test line 4


My current terrible hack to accomplish this (at least on files that don't have 10000+ consecutive lines with no matches) is:
$ grep -B 9999 -A 9999 test test


If grep can't accomplish this, is there another command-line tool that offers the same functionality? I've fiddled with ack, but it doesn't seem to have an option for it either
by

1 Answer

Bharatgxwzm
grep --color -E "test|$" yourfile

What we're doing here is matching against the $ pattern and the test pattern, obviously $ doesn't have anything to colourize so only the test pattern gets color. The -E just turns on extended regex matching.

You can create a function out of it easily like this:
highlight () { grep --color -E "$1|$" "${@:1}" ; }

Login / Signup to Answer the Question.