Change each symbol excluding variables in bash using sed & regex

时间:2022-10-20 11:45:20

I need to change string like

我需要更改字符串

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

示例\%^ $ variable $ {array [$ element]}

Into string like

变成字符串就好

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

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

So, I need to escape EACH symbol except for variables in those 2 cases.

因此,除了这两种情况中的变量之外,我需要转义EACH符号。

Also, and this is tricky, I need to escape them twice, so that the result will be achieved by using command:

此外,这是棘手的,我需要两次逃避它们,以便通过使用命令实现结果:

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

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

Also, I have achieved escaping ALL the characters:

此外,我已经实现了逃避所有角色:

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

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

So, the question is how to NOT escape $variables?

那么,问题是如何不逃避$变量?

I am pretty good at regex, so just working example will suffice. But any explanations are welcome. Also, I'll post the answer here if I'd find it faster than any of you. I think it's an interesting puzzle to solve :)

我很擅长正则表达式,所以只需要工作实例即可。但任何解释都是受欢迎的。另外,如果我发现它比你们任何人都快,我会在这里发布答案。我认为这是一个有趣的难题来解决:)

1 个解决方案

#1


2  

If you can use perl then it can be done easily like this:

如果您可以使用perl,那么可以像这样轻松完成:

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

RegEx演示


Update: Here is how this can be done using gnu-awk:

更新:以下是使用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\

#1


2  

If you can use perl then it can be done easily like this:

如果您可以使用perl,那么可以像这样轻松完成:

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

RegEx演示


Update: Here is how this can be done using gnu-awk:

更新:以下是使用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\