Sunday, April 28, 2024
1
rated 0 times [  1] [ 0]  / answers: 1 / hits: 443  / 2 Years ago, fri, august 19, 2022, 7:21:01

I do not know why this does not work:


echo -e "$(echo "This is an uncolored text" | sed "s/{This is an uncolored text}/{This is an 033[0;34uncolored text033[0m}/g")"

but this works well:


echo "$(echo "Hello World" | sed "s/Hello/Hi/g")"

May you explain to me?


More From » command-line

 Answers
7

There are a number of issues.


First, the braces {...} in your sed expression are not matched by anything in the input. In a sed Basic Regular Expression, braces are literal, while in an Extended Regular Expression they surround a quantifier of the form {n,m}. They are never used for grouping.


Second, your color sequence is malformed - the opening needs to be 033[0;34m rather than 033[0;34


Third, the backslash character is special in sed - in particular, a backslash followed by a decimal digit on the RHS of a substitution is a backreference to a capture group; at least in GNU sed, 0 refers to the whole captured LHS equivalent to the special replacement token & so for example


$ echo foo | sed 's/foo/033bar/'
foo33bar

To pass a literal to the outer echo -e you'd need inside the sed replacement string.


Finally, is also special to the shell, so inside "soft" double quotes needs an additional backslash. So either:


echo -e "$(echo "This is an uncolored text" | 
sed "s/This is an uncolored text/This is an 33[0;34muncolored text33[0m/")"

or (replacing the inner double quotes with 'strong' single quotes):


echo -e "$(echo "This is an uncolored text" | 
sed 's/This is an uncolored text/This is an 033[0;34muncolored text033[0m/')"

Note that you don't need the g modifier to make a single replacement per line.


See also What characters do I need to escape when using sed in a sh script?


[#814] Sunday, August 21, 2022, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
weamp

Total Points: 197
Total Questions: 115
Total Answers: 92

Location: Mauritania
Member since Sun, May 7, 2023
1 Year ago
;