BASH:转义字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47563387/
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
BASH: unescape string
提问by Christopher
Suppose I have the following string:
假设我有以下字符串:
"some\nstring\n..."
And it displays as one line when catted in bash. Further,
当在 bash 中 catted 时,它显示为一行。更远,
string_from_pipe | sed 's/\\/\/g' # does not work
| awk '{print some
string
}'
| awk '{s = s='some\nstring\n...'
printf '%b\n' "$s"
; print s}'
| awk '{s = some
string
...
; printf "%s",s}'
| echo $ s="some\nstring\n..."
$ echo "$s"
some\nstring\n...
| sed 's/\(.)//g'
# all have not worked.
How do I unescape this string such that it prints as:
我如何取消转义这个字符串,使其打印为:
$ printf "$s\n"
some
string
...
Or even displays that way inside a file?
或者甚至在文件中以这种方式显示?
采纳答案by Charles Duffy
POSIX sh
provides printf %b
for just this purpose:
POSIX正是为此目的而sh
提供printf %b
的:
$ echo "$s" | sed 's/\n/\n/g'
some
string
...
...will emit:
...会发出:
$ echo "$s" | awk '{gsub(/\n/, "\n")} 1'
some
string
...
More to the point, the APPLICATION USAGE section of the POSIX spec for echo
explicitly suggests using printf %b
for this purpose rather than relying on optional XSI extensions.
更重要的是,POSIX 规范echo
的 APPLICATION USAGE 部分明确建议printf %b
为此目的使用,而不是依赖可选的 XSI 扩展。
回答by John1024
As you observed, echo
does not solve the problem:
正如您所观察到的,echo
并不能解决问题:
${myvar//\n/$'\n'}
You haven't mentioned where you got that string or which escapes are in it.
你还没有提到你从哪里得到那个字符串或其中有哪些转义。
Using bash
使用 bash
If the escapes are ones supported by printf
, then try:
如果转义是由 支持的printf
,则尝试:
$ myvar='hello\nworld\nfoo'
$ echo "${myvar//\n/$'\n'}"
hello
world
foo
$
Using sed
使用 sed
$ s="some\nstring\n..." && echo -e "$s"
some
string
...
Using awk
使用 awk
-e enable interpretation of the following backslash escapes
[...]
\a alert (bell)
\b backspace
\c suppress further output
\e escape character
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\ backslash
##代码##nnn the character whose ASCII code is NNN (octal). NNN can be 0 to 3 octal digits
\xHH the eight-bit character whose value is HH (hexadecimal). HH can be one or two hex digits
回答by psmears
If you have the string in a variable (say myvar
), you can use:
如果您在变量中有字符串(例如myvar
),您可以使用:
For example:
例如:
##代码##(Note: it's usually safer to use printf %s <string>
than echo <string>
, if you don't have full control over the contents of <string>
.)
(注意:如果您不能完全控制 . 的内容,则使用它通常printf %s <string>
比更安全。)echo <string>
<string>