I have a string and I need to add #, in the beginning,i.e. convert [ -n "$ID" -a "$ID" -le 200 ] && return to #[ -n "$ID" -a "$ID" -le 200 ] && return. I can use below command:
echo '[ -n "$ID" -a "$ID" -le 200 ] && return'| sed -n -e 's/\[ -n "$ID" -a "$ID" -le 200 \] && return/#&/p'
It works. Now I have two questions, regarding E, flag.
For the string
[ -n "$ID" -a "$ID" -le 200 ], if I escape brackets, it does not work; however, it works when I do not escape them i.e.sed -n -E 's/[ -n "$ID" -a "$ID" -le 200 ]/#&/p'works while
sed -n -E 's/\[ -n "$ID" -a "$ID" -le 200 \]/#&/p'doesn't work.
For, the full string
[ -n "$ID" -a "$ID" -le 200 ] && return, it gives me wrong answer, when I do not escape them:echo '[ -n "$ID" -a "$ID" -le 200 ] && return'| sed -n -E 's/[ -n "$ID" -a "$ID" -le 200 ] && return/#&/p'It gives me output:
[ -n "$ID" -a "$ID" -le 200 #] && return
I want to know how it is working.
[and]must be escaped in both BRE and ERE (otherwise they define a range expression). As to why you get no output when escaping them and using ERE, I think it's a difference in how$is treated between BRE and ERE when it's not the final character of a pattern - see for example Bash sed replace double dollar sign $$ extended regular expressions-Eand-eoptions are two completely different and unrelated things. they are not alternate versions of each other.-etells sed that the next argument is a script to be run.-Etells sed to use extended regular expressions (ERE) instead of sed's default of basic regular expressions (BRE).