Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escaping the '\' character in the replacement string in a sed expression

I am trying to take a line of text like

    13) Check for orphaned Path entries

and change it to (I want the bash color codes to colorize the output, not display on the screen)

\033[32m*\033[0m Check for orphaned Path entries

with bash color codes to colorize the asterisk to make it stand out more. I have a sed command that does most of that, except it doesn't handle the color codes correctly since it sees them as references to replacement text.

What I have so far:

sed "s/ *13) \(.*\)/ \033[32m*\033[0m \1/"

which produces the following output when run on the string I gave at the beginning:

   13) Check for orphaned Path entries33[32m*  13) Check for orphaned Path entries33[0m Check for orphaned Path entries

It is taking the \0 of the \033 and replacing it with the original string. Doubling the backslashes in the replacement string doesn't make a difference; I still get the same output text.

How do I insert bash color escapes into a sed replacement expression?

like image 275
Chris Lieb Avatar asked Jun 30 '09 15:06

Chris Lieb


People also ask

How do you escape special characters in sed?

Put a backslash before $. */[\]^ and only those characters (but not inside bracket expressions).

How do you escape a backslash in sed?

Use single quotes for sed and you can get away with two backslashes. echo "sample_input\whatever" | sed 's/\\/\//' Hopefully someone will come up with the correct explanation for this behavior.


2 Answers

Chances are that the sed you are using doesn't understand octal, but it may understand hex. Try this version to see if it works for you (using \x1b instead of \033):

sed "s/ *13) \(.*\)/ \x1b[32m*\x1b[0m \1/"
like image 173
Dennis Williamson Avatar answered Nov 04 '22 19:11

Dennis Williamson


your '\033' is in fact a single ESC (escape) character, to output this you may use any one of the following:

  • \o033
  • \d027
  • \x1B
  • \c[ for CTRL-[
like image 24
Hasturkun Avatar answered Nov 04 '22 21:11

Hasturkun