Coloring matched portions with GNU grep, sed and awk
You might already know how to use the --color
option to highlight matched portions with GNU grep
. In this post, you'll see how to use ANSI escape sequences to format matched portions with GNU sed
and GNU awk
.
GNU grep🔗
Consider this sample input file:
$ cat fruits.txt
banana mango cherry pineapple
grape fig apple dragonfruit papaya
watermelon cashew tomato orange
almond lime grapefruit walnut
The output for grep --color -wE '[ago]\w+' fruits.txt
is shown below:
See this section from my ebook on GNU grep
for more details about this option. ripgrep has a more featured support for color formatting, see this section for an example.
Formatting with ANSI escape sequences🔗
Here are some examples to show how you can format text in the terminal using ANSI escape sequences:
Your choice of formatting goes between \033[
and m
. You can use 01
for bold, 03
for italics and 04
for underline. 31
is for the color red, 32
for green and 34
for blue. Multiple formats can be specified by separating the parameters with a semicolon. Using 0
turns off the format (otherwise, it will persist in the current terminal session until turned off).
If you find a file that has accidentally saved such escape sequences, you can use cat -v
to identify them.
$ echo 'one (two) three' | grep --color=always '(two)' | cat -v
one ^[[01;31m^[[K(two)^[[m^[[K three
See also:
Note that you can also use \e
instead of \033
in the above examples. However, that will not work with the GNU awk
examples shown below.
GNU sed🔗
With GNU sed
, you'll need to use \o
to specify an octal escape sequence. Here's an example:
Here's an example for processing lines bounded by distinct markers:
$ cat blocks.txt
mango
icecream
--start 1--
dragon 1234
unicorn 6789
**end 1**
have a nice day
--start 2--
a b c
apple banana cherry
**end 2**
par,far,mar,tar
GNU awk🔗
With GNU awk
, you can embed the ANSI escape sequences in a string similar to the printf
example seen earlier.
Here's a field processing example:
$ cat marks.txt
Dept Name Marks
ECE Raj 53
ECE Joel 62
EEE Moi 68
CSE Surya 81
EEE Tia 59
ECE Om 92
CSE Amy 67
$ cat filter.txt
ECE 70
EEE 65
CSE 80
Linux CLI ebooks🔗
Check out my ebooks if you are interested in learning more about Linux CLI basics, coreutils, text processing tools like GNU grep
, GNU sed
, GNU awk
and perl
.