Question

I'm processing input (from sources like, but limited to, ls -la --color) and underlining certain sections of the text. I don't process these inputs character-by-character, but with lots of regular expressions, which makes it rather difficult to track whether the substring I'm affecting is already colored or in bold. If I have a red block of text, and I want to underline some part of it, I might do something like:

s/(123)/\033[4m\1\033[0m/g

(My expressions are much more complex. In reality, matches extracted, processed on their own, and further broken down and analyzed. This isn't something that can be done by changing the expression I've given here.)

The code above would replace all ocurrences of 123 with [UNDERLINE_START]123[FORMAT_RESET]. Unfortunately, the reset also turns off the coloring of text. It would save me a great deal of headache if I could just turn off the underlining when that is all I want to disable, but I'm pretty sure there's no way to do that. Can anyone tell me that I'm wrong?

EDIT: I could simplify the question by asking: if I want to turn off underlining, can I do that without affecting the current text color, since that color could have been set long before my script even started executing, and I don't have a way to detect what that color is?

Was it helpful?

Solution

Nobody seems to document it, but adding 20 to the decorator codes will turn them off:

  echo -e "\\033[34;4m" underlined "\\033[24m" not underlined
  echo -e "\\033[34;1m" bold "\\033[2m" not bold
  echo -e "\\033[34;2m" dark "\\033[22m" not dark
  echo -e "\\033[34;7m" inverse "\\033[27m" not inverse

OTHER TIPS

Instead of those hard-coded escape sequences, use:

tput smul # set underline
tput rmul # remove underline

tput smso # set bold on
tput rmso # remove bold

tput setaf 1 #red
tput setaf 2 #green

...
tput cup 0 0 # move to pos 0,0

Refer to "man terminfo" and "man tput" for complete descriptions of these commands.

Examples :

function f_help
{
c_green=$(tput  setaf 2      2>/dev/null)
c_reset=$(tput  sgr0         2>/dev/null)
c_bold=$(tput smso           2>/dev/null)
echo "${c_bold}DESCRIPTION${c_reset} : ...."
}


echo "${c_green}GREEN ${c_underline} GREEN AND UNDERLINED${c_nounderline} GREEN AGAIN${c_reset} PLAIN BLACK TEXT"

The ${c_underline} escape sequence doesn't affect the color of the text; it only turns underlining on. ${c_nounderline} only turns underlining off.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top