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

爷,独闯天下 提交于 2019-11-29 20:35:33

问题


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?


回答1:


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/"



回答2:


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-[



回答3:


Double the backslashes in the replacement string, AND use single instead of double quotes around the sed expression:

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

This prevents the shell from interfering with the sed behaviour.

~~~~~~~

Update:

Use a script to achieve color cleanly:

colorize.sh

#!/bin/sh

HIGHLIGHT=`echo -e '\033[32m'`
NORMAL=`echo -e '\033[0m'`

sed "s/ *13) \(.*\)/ $HIGHLIGHT*$NORMAL \1/" yourinputtext



回答4:


I had the same problem and I solved in this way.

You can try to change your code:

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

into this:

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

The basic idea is to use 'echo' to print the escape command. It worked for me,




回答5:


I use gawk

gawk -v string1=$STRING1 -v IGNORECASE=1 ' { gsub ( string1 , "\033[1m&\033[0m" ) ; print } '



回答6:


Try this :

sed  "s/ *13) \(.*\)/ \\\\033 \1/"

i.e. slash-slash-slash-slash-033



来源:https://stackoverflow.com/questions/1064352/escaping-the-character-in-the-replacement-string-in-a-sed-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!