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

时间:2014-09-21 10:52:00

标签: linux bash shell printf

我正在尝试在shell中使用printf格式化字符串,我将从文件中获取输入字符串,其中包含%,',"",,\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;

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

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也有问题。

4 个答案:

答案 0 :(得分:6)

尝试

printf "%s\n" "$string"

请参阅printf(1)

答案 1 :(得分:2)

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

答案 2 :(得分:1)

您可以使用$' '括起换行符和制表符,然后使用普通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()语法。 #39;我知道。此外,string的范围也可能是使用它的函数的本地范围,所以我也改变了它。

输出:

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

答案 3 :(得分:1)

为了方便在谷歌搜索“bash printf转义”后点击第一个搜索结果到达这里的人,使用printf生成bash转义文本的正确方法是:

printf " %q" "here is" "a few\n" "tests"

哪些输出(没有尾随换行符):

 here\ is a\ few\\n tests