I can do the following to see if some word is available in the output of “cat”:
cat filename | grep word
This filters the output and shows only those lines which contain “word”. Now, is it possible to only highlight the “word” in the output, without dropping other lines?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can grep for an EOL along with your real query (if you already have an alias for grep to use --color, as is default in many distributions, you can omit it in the following examples):
grep --color=auto 'word|$' file
Since the EOL is not a real character, it won’t highlight anything, but it will match all lines.
If you would prefer not to have to escape the pipe character, you can use extended regular expressions:
grep -E --color=auto 'word|$' file
Method 2
If you haven’t GNU grep available, here is something more portable:
grepc()
{
pattern=$1
shift
esc=$(printf "33")
sed 's"'"$pattern"'"'$esc'[32m&'$esc'[0m"g' "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="341074">[email protected]</a>"
}
You can customize the color using one of these codes
30m black 31m red 32m green 33m yellow 34m blue 35m magenta 36m cyan 37m white
Using 7m instead of a color code will put the string in reverse video.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0