打印一个字符串,其特殊字符打印为文字转义序列

asy*_*ote 5 bash shell

我在shell/bash脚本中有一个字符串.我想打印字符串,其中包含所有"特殊字符"(例如换行符,制表符等)作为文字转义序列打印(例如,打印换行符,打印\n选项卡\t,等等).

(不确定我是否使用了正确的术语;该示例应该有希望澄清事情.)

期望的......的输出

a="foo\t\tbar"
b="foo      bar"

print_escape_seq "$a"
print_escape_seq "$b"
Run Code Online (Sandbox Code Playgroud)

...是:

foo\t\tbar
foo\t\tbar
Run Code Online (Sandbox Code Playgroud)
  1. $a并且$b是从文本文件中读入的字符串.
  2. 有之间有两个制表符foo,并bar$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"
Run Code Online (Sandbox Code Playgroud)

输出是:

foo\t\tbar
foo bar
Run Code Online (Sandbox Code Playgroud)

所以,它不起作用$b.

是否有完全直接的方法来完成这个我完全错过了?

Fro*_*bit 8

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")
Run Code Online (Sandbox Code Playgroud)

这是输出

testval=$'hello\t\tworld'
The encoded value of testval is hello\t\tworld
Run Code Online (Sandbox Code Playgroud)


use*_*028 3

您将需要为要替换的每个二进制值创建搜索和替换模式。像这样的东西:

#!/bin/bash

esc() {
    # space char after //
    v=${1// /\\s}   
    # tab character after //
    v=${v// /\\t}
    echo $v
}
esc "hello world"
esc "hello  world"
Run Code Online (Sandbox Code Playgroud)

这输出

hello\sworld
hello\tworld
Run Code Online (Sandbox Code Playgroud)