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

我正在尝试在shell中使用printf格式化string,我将从文件中获取inputstring,其中包含特殊字符(如%,',"",,\user, \tan等)。

如何转义inputstring中的特殊字符?

例如

 #!/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; 

我期待这将打印在我想要的格式

 The path to K:\Users\ca, this is good The second line 123 It also has to be 100% nice than %99 

但是,它给予意想不到的放

 ./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 

那么我怎样才能摆脱特殊字符,而打印。 echo -e也有问题。

你可以使用$' '来包装换行符和制表符,然后一个普通的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 

我还对你的脚本做了一些其他的小改动。 除了使您的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 

尝试

 printf "%s\n" "$string" 

参见printf(1)