Change each symbol excluding variables in bash using sed & regex -


i need change string like

example \%^ $variable ${array[$element]}

into string like

\e\x\a\m\p\l\e\ \\\%\^\ $variable\ ${array[$element]}

so, need escape each symbol except variables in 2 cases.

also, , tricky, need escape them twice, result achieved using command:

string='example \%^ $variable ${array[$element]}' echo `echo $string | sed 'magic'

also, have achieved escaping characters:

echo $(echo $string | sed -r -e 's/(.)/\\\\\1/g')

so, question how not escape $variables?

i pretty @ regex, working example suffice. explanations welcome. also, i'll post answer here if i'd find faster of you. think it's interesting puzzle solve :)

if can use perl can done this:

s='example \%^ $variable"abc" ${array[$element]} ${var}this' perl -pe 's/\$(?:{.*?}|\w+)(*skip)(*f)|(.)/\\$1/g' <<< "$s" 

output:

\e\x\a\m\p\l\e\ \\\%\^\ $variable\"\a\b\c\"\ ${array[$element]}\ ${var}\t\h\i\s 

regex demo


update: here how can done using gnu-awk:

awk -v rs='\\$({.*?}|[[:alnum:]_]+)' '{gsub(/./, "\\\\&"); printf "%s%s", $0, rt}' <<< "$s" \e\x\a\m\p\l\e\ \\\%\^\ $variable\"\a\b\c\"\ ${array[$element]} ${var}\t\h\i\s\ 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -