在使用printf时如何在shell脚本中转​​义特殊字符?

Sar*_*ath 6 linux bash shell printf

我正在尝试使用printfshell 格式化字符串,我将从文件中获取输入字符串,其中包含特殊字符等%,',"",,\user, \tan.

如何转义输入字符串中的特殊字符?

例如

#!/bin/bash
# 

string='';
function GET_LINES() {

   string+="The path to K:\Users\ca, this is good";
   string+="\n";
   string+="The second line";
   string+="\t";
   string+="123"
   string+="\n";
   string+="It also has to be 100% nice than %99";

   printf "$string";

}

GET_LINES;
Run Code Online (Sandbox Code Playgroud)

我希望这将以我想要的格式打印

The path to K:\Users\ca, this is good
The second line   123
It also has to be 100% nice than %99
Run Code Online (Sandbox Code Playgroud)

但它给出了意想不到的结果

./script: line 14: printf: missing unicode digit for \U
The path to K:\Users\ca, this is good
The second line 123
./script: line 14: printf: `%99': missing format character
It also has to be 100ice than 
Run Code Online (Sandbox Code Playgroud)

那么如何在打印时摆脱特殊字符呢?echo -e也有问题.

Jon*_*yer 10

为了让那些通过点击谷歌搜索“bash printf escaped”后的第一个搜索结果到达这里的人的利益,%qprintf 使用格式化程序来生成 bash 转义的文本。

例如:

$ printf "<<%q>>\n" 'foe fum' "fee fie"$'\n'
<<foe\ fum>>
<<$'fee fie\n'>>
Run Code Online (Sandbox Code Playgroud)

man printf

%q     ARGUMENT is printed in a format that can be reused as shell
       input,  escaping  non-printable  characters with the 
       proposed POSIX $'' syntax.
Run Code Online (Sandbox Code Playgroud)

  • 只需添加对“%q”的解释 - 使 printf 以可重用为 shell 输入的格式输出相应的参数。https://man.archlinux.org/man/bash.1.en#printf (3认同)

小智 8

我可以说“man printf”清楚地表明“%”字符必须通过另一个“%”进行转义,因此 printf“%%” 会产生单个“%”


Tom*_*ech 3

您可以使用$' '将换行符和制表符括起来,然后简单的echo就足够了:

#!/bin/bash 

get_lines() {    
   local string
   string+='The path to K:\Users\ca, this is good'
   string+=$'\n'
   string+='The second line'
   string+=$'\t'
   string+='123'
   string+=$'\n'
   string+='It also has to be 100% nice than %99'

   echo "$string"
}

get_lines
Run Code Online (Sandbox Code Playgroud)

我还对您的脚本做了一些其他的小改动。除了将 FUNCTION_NAME 设置为小写外,我还使用了更广泛兼容的函数语法。在这种情况下,没有太大的优势(因为字符串无论如何都是 bash 扩展),但据我所知,$' '没有理由使用该语法。function func()另外, 的范围string也可能是使用它的函数的本地范围,所以我也改变了它。

输出:

The path to K:\Users\ca, this is good
The second line 123
It also has to be 100% nice than %99
Run Code Online (Sandbox Code Playgroud)