bash 在bash中转义字符串的命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2854655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:16:54  来源:igfitidea点击:

Command to escape a string in bash

bashescaping

提问by User1

I need a bash command that will convert a string to something that is escaped. Here's an example:

我需要一个 bash 命令,它将字符串转换为转义的内容。下面是一个例子:

echo "hello\world" | escape | someprog

Where the escape command makes "hello\world"into "hello\\\world". Then, someprog can use "hello\\world"as it expects. Of course, this is a simplified example of what I will really be doing.

转义命令在哪里"hello\world"变成"hello\\\world". 然后,someprog 可以"hello\\world"按预期使用。当然,这是我真正要做的事情的一个简化示例。

回答by Paused until further notice.

In Bash:

在 Bash 中:

printf "%q" "hello\world" | someprog

for example:

例如:

printf "%q" "hello\world"
hello\world

This could be used through variables too:

这也可以通过变量使用:

printf -v var "%q\n" "hello\world"
echo "$var"
hello\world

回答by Fritz G. Mehner

Pure Bash, use parameter substitution:

纯 Bash,使用参数替换:

string="Hello\ world"
echo ${string//\/\\} | someprog

回答by Michael Aaron Safyan

You can use perl to replace various characters, for example:

您可以使用 perl 替换各种字符,例如:

$ echo "Hello\ world" | perl -pe 's/\/\\/g'
Hello\ world

Depending on the nature of your escape, you can chain multiple calls to escape the proper characters.

根据转义的性质,您可以链接多个调用来转义正确的字符。