Display all output but highlight search matches
Solution 1:
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.
Solution 2:
Add option -z
to your GNU grep command:
cat testfile | grep --color=always -z 'hello'
or shorter
grep --color=always -z 'hello' testfile
Solution 3:
Similarly to previous answer, you can catch all $
end of lines:
cat testfile | grep --color -E "hello|$"
-E
(or --extended-regexp
) means that special characters must be escaped with \
. When using it, |
will be treated as regex "OR" condition.
Grep |$
will also catch and print all lines which has an end, but since $ is a hidden character, it cannot be highlighted.
Update:
If you'd like to print all output, but also return exit code, whether match was found or not, you can use perl command:
cat testfile | \
perl -pe 'BEGIN {$status=1} END {exit $status} $status=0 if /hello/;'
If you prefer sed - Here's an example how to highlight all matches + return exit code if no match found: https://askubuntu.com/a/1200851/670392
Solution 4:
This one works with GNU grep as well as with grep on FreeBSD:
grep --color=always 'hello\|$'
It matches the text "hello" or (\|
) the non-printable null string at the end of each line ($
). That's why each line gets printed but only "hello" is highlighted.
Chances are you already have --color=auto
configured in your shell. Then you most likely don't need to specify --color=always
:
grep 'hello\|$'
You can also simpler version by using egrep
(with extended regular expressions), where |
for the "or" expression doesn't need to be escaped:
egrep 'hello|$'