For my work, I'm frequently searching for patterns in files. Generally I use the grep --color=auto
to color the search pattern. Now when I'm searching for multiple patterns, all of which should be present in a line, I use grep pattern1 file|grep pattern2|grep pattern3
or awk '/pattern1/&&/pattern2'
. But this way, in grep I lose the coloring which is highly helpful for me, or in awk, I don't know any way to color only the pattern string. When it becomes too troublesome, I use grep pattern1 file|grep pattern2|grep pattern3|grep -E "pattern1|pattern2|pattern3"
.
So is there any way in grep to mention multiple patterns in and condition? ( I think regular expressions should support it, but could not find any, specially the ordering of patterns are not fixed)
Or is there any way to color print the awk search patterns?
Any short compact approach is welcome (for I will be using many times a day )
You could build your own shell script/function
using awk
and escape codes:
Given the file Awk color text
the following will print the matched word Awk
in cyan:
$ awk '/Awk/{gsub(/Awk/,"\033[1;36m&\033[1;000m");print}' file
Awk color test
This principle can easily be extended for multiple patterns added This line ends here
to line one.
$ awk '/Awk/&&/This/{gsub(/Awk|This/,"\033[1;36m&\033[1;000m");print}' file
Awk color test This line ends here.
Check out here for some more information on shell colours.
You can use --color=always
when piping from grep to retain color:
grep pat1 --color=always | grep pat2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With