我在 shell/bash 脚本中有一个字符串。我想打印字符串,并将其所有“特殊字符”(例如换行符、制表符等)打印为文字转义序列(例如换行符打印为\n
,选项卡打印为\t
, 等等)。
(不确定我是否使用了正确的术语;该示例应该能够澄清问题。)
Example
期望的输出...
a="foo\t\tbar"
b="foo bar"
print_escape_seq "$a"
print_escape_seq "$b"
...is:
foo\t\tbar
foo\t\tbar
-
$a
and $b
是从文本文件中读入的字符串。
- 之间有两个制表符
foo
and bar
in the $b
多变的。
一次尝试
这是我尝试过的:
#!/bin/sh
print_escape_seq() {
str=$(printf "%q\n" $1)
str=${str/\/\//\/}
echo $str
}
a="foo\t\tbar"
b="foo bar"
print_escape_seq "$a"
print_escape_seq "$b"
输出是:
foo\t\tbar
foo bar
所以,它不适用于$b
.
有没有一种完全简单的方法来完成这个任务,但我完全错过了?
Bash 有一个字符串引用操作 ${var@Q}
这是一些示例代码
bash_encode () {
esc=${1@Q}
echo "${esc:2:-1}"
}
testval=$(printf "hello\t\tworld")
set | grep "^testval="
echo "The encoded value of testval is" $(bash_encode "$testval")
这是输出
testval=$'hello\t\tworld'
The encoded value of testval is hello\t\tworld
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)