You can do this with just grep
. Where file.txt
is your file and word
is the text you want to highlight, you can use:
grep --color -E 'word|$' file.txt
This matches and highlights occurrences of word
. In addition, it alternatively (|
) matches and highlights the empty string at the end of each line ($
). But since that string is empty, no extra text is actually highlighted.
Also matchingMatching $
in addition to word
serves the purpose of ensuring every line contains a match. Then grep
prints every line, even without the -A
, -B
, or -C
options or any calls to other utilities.
The -E
flag makes grep
interpret its pattern argument as ana POSIX extended regular expression (ERE). Depending on what characters are in word
, you may want to make it use a basic regular expression (BRE) instead. Although alternation with |
is not officially part of POSIX basic regular expressions, grep
implementations often support it as an extension with \|
:1
grep --color 'word\|$' file.txt
In particular, on GNU/Linux systems you have GNU Grep, which supports this. If you are relying on --color
, you can likely rely on this behavior too.
These commands are simpler than the way in goldilocks's answer. But the technique in that answer does have a distinct advantage in some circumstances. Since the methods here use |
and $
, they have to really be regular expressions, rather than fixed strings. However, with goldilocks's method, you can add the -F
flag. Then word
can contain whatever text you like, even \
, provided you quote word
properly to ensure the shell passes it to grep
unmodified.
For example, you can use:
grep --color -FC "$(wc -l < file.txt)" 'word' file.txt
For further reading, see Convince grep to output all lines, not just those with matches (as steeldriver suggested).
1As far as the standard (IEEE Std 1003.1-2008) specifies, alternation is a feature of ERE (via |
), but it is not a feature of BRE. But implementations are permitted to interpret \|
as they wish, and many interpret it as alternation:
Some implementations have extended the BRE syntax to add alternation. For example, the subexpression "
\(foo$\|bar\)
" would match either "foo
" at the end of the string or "bar
" anywhere. The extension is triggered by the use of the undefined "\|
" sequence.