banner

For a full list of BASHing data blog posts see the index page.     RSS


Emphasising text in the terminal

Working with plain text data in a terminal means that you're not distracted by formatting. The characters are all the same colour and font weight, and there's no highlighting. Sometimes, however, a bit of emphasis in a particular string would be welcome. This post looks at ways to get that emphasis with ANSI codes.


It's a good idea to emphasise the important parts of a script output, here for example in the "fldnos" script that checks for broken fields in a data table:

high0

This is done in the script by putting ANSI color codes into variables, then using the variables to color and de-color the selected string, e.g.:

high0a

The GNU grep command comes with built-in emphasis. If grep is aliased to grep --color=auto or grep --color=always, then a searched-for string will be bold and red:

high1

The emphasis is bold and red because grep's default coloring for a searched-for string ("ms") is the ANSI code "1;31"(= bold;red) in the environment variable GREP_COLORS. I can temporarily change that emphasis to bold with a light yellow background ("ms=1;103") by modifying GREP_COLORS, doing my search, then reversing the change with unset. With "ms="1;4" I can temporarily get bold and underlined:

high2

This setting and unsetting of GREP_COLORS is best put in a function, for example:

cgrep() { export GREP_COLORS='ms=1;103'; grep -E "$1" "$2"; unset GREP_COLORS; }

I've used grep -E in "cgrep" to allow for extended regular expressions. The unsetting of GREP_COLORS also means that I can use ordinary grep in the same terminal session and get the usual bold-and-red emphasis:

high3

In the second "cgrep" command I'm looking for repeated words. The regex matches 1 or more alphabetic characters ([[:alpha:]]+) with a word boundary (\b) fore and aft, followed by a space, followed by the same word again in the form of a backreference (\1).


In a BASHing data post about mutating DNA sequences a few weeks back I showed how I could emphasise the result of a sed replacement. For uncomplicated replacements this can be done with ANSI color codes and BASH string expansion, but a safer approach is to save the codes and their escapes in shell variables:

high4

In some situations I might want to emphasise a replacement operation that could be done, rather than actually do a replacement. sed is again my friend:

high5

The sed emphasis trick is also one of the few ways I know to visualise no-break spaces and soft hyphens in the terminal. The "aaa bbb ccc ddd" string in the next screenshot has two no-break spaces, but these print as plain spaces unless I do a sed emphasis on them:

high6

Last update: 2019-12-13
The blog posts on this website are licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License