Using color output for awk or grep to search for multiple patterns and conditions

For my work, I often look for patterns in files. I usually use grep --color=auto to color the search pattern. Now, when I search for several patterns, all of which should be present in the string, I use grep pattern1 file|grep pattern2|grep pattern3 or awk '/pattern1/&&/pattern2' . But in this way, in grep, I lose color, which is very useful for me, or in awk, I don’t know how to color only a template line. When this gets too troublesome, I use grep pattern1 file|grep pattern2|grep pattern3|grep -E "pattern1|pattern2|pattern3" .

So, is there a way to grep to specify multiple patterns and conditions? (I think that regular expressions should support it, but could not find them, especially the ordering of the patterns is not fixed)

Or is there a way to color print awk search patterns?

Any short compact approach is welcome (I will use it many times a day)

+7
source share
2 answers

You can use --color=always when the pipeline from grep retains color:

 grep pat1 --color=always | grep pat2 
+6
source

You can create your own shell script/function using awk and escape codes:

Given the Awk color text file, the following will print the consistent word awk in cyan:

 $ awk '/Awk/{gsub(/Awk/,"\033[1;36m&\033[1;000m");print}' file Awk color test 

This principle can be easily extended to add several This line ends here patterns to line 1.

 $ awk '/Awk/&&/This/{gsub(/Awk|This/,"\033[1;36m&\033[1;000m");print}' file Awk color test This line ends here. 

Check here for more information on shell colors.

+5
source

All Articles