abasu
abasu

Reputation: 2524

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

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 )

Upvotes: 11

Views: 6229

Answers (3)

trellem
trellem

Reputation: 31

You could also use curly braces for parameter expansion:

grep --color=always -e{pat1,pat2}

which effectively is the same as:

grep --color=always -e foo -e bar

Note this will return results with pat1 AND/OR pat2.

(I don't have enough reputation points to add this post as a comment)

Upvotes: 0

Chris Seymour
Chris Seymour

Reputation: 85883

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.

Upvotes: 6

perreal
perreal

Reputation: 98118

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

grep pat1 --color=always | grep pat2

Upvotes: 10

Related Questions