Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using colored output for awk, or grep multiple pattern search in and condition

Tags:

grep

bash

awk

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 )

like image 286
abasu Avatar asked Apr 11 '13 09:04

abasu


2 Answers

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.

like image 175
Chris Seymour Avatar answered Nov 13 '22 00:11

Chris Seymour


You can use --color=always when piping from grep to retain color:

grep pat1 --color=always | grep pat2
like image 26
perreal Avatar answered Nov 13 '22 02:11

perreal