Unix Bash script to embolden/underline/italicize specific text

user536067 picture user536067 · Dec 11, 2010 · Viewed 14.1k times · Source

I've been trawling the web trying to find examples of Unix Bash script that can handle basic text styling (bold/underline/italics), but can't find anything? Is such a thing possible to do?

For example:

  1. Embolden/Underline/Italicize all lines ending in ":"?
  2. (Turn off) Embolden/Underline/Italicize all lines ending in ":"?

I want to set it up as a Service via Automator; so using /bin/bash and actioning on "selected text" (in a rich-text-compatible file, of course).

Answer

Chris Cashwell picture Chris Cashwell · Dec 11, 2010

Basically, you want to do declare some variables with the styling code--something like this:

underline=`tput smul`
nounderline=`tput rmul`
bold=`tput bold`
normal=`tput sgr0`

then you can call these for use in your output using the variables, like this:

echo "${bold}bold${normal} text stands out!"
echo "${underline}underlined${nounderline} text does, too."

As far as automating it to apply to all lines beginning with a specific character, you're better off just using the variables as shown above. Besides using this method just being easier, it's also cleaner and more usable. For example, when using this method you have the ability to style any number of words in a given output string differently, so as to emphasize a specific word, not the entire sentence (unless of course that's your goal).

For more information, you should check out http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x405.html and/or man tput