Highlight console search output, while displaying entire command output
When I use e.g. cat file.txt | grep --color=tty "pattern"
I get the pattern I search highlighted. When I want some more context around each hit, grep has the -A
, -B
and -C
parameters.
However, I want to display the whole file (or whatever command output) and highlight a certain pattern. Does such a highlight command or tool exist?
There was an answer on unix.stackexchange.com that had this neat trick:
grep -E --color 'pattern|$' file.txt
or
grep --color 'pattern\|$' file.txt
which matches your pattern or the end-of-line on each line. Only the pattern is highlighted.
I like ack.
ack --passthru somepattern filename
It's like grep, but better. It highlights by default, and with the --passthru
option it shows the entire file (or standard input) instead of only the matching lines.
I also recommend the use of less
(or such), but I want to show you a more didactical solution. Once you have defined this function:
function highlight() { sed "s/$1/`tput smso`&`tput rmso`/g" "${2:--}" }
You can use it this way:
command | highlight pattern
highlight pattern file.txt
Note: This version is case sensitive, to change that just append i
after g
in the sed
expression.