【发布时间】:2014-09-21 10:52:00
【问题描述】:
我正在尝试在 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 也有这个问题。
【问题讨论】:
-
%在参数中的可能性正是为什么你永远不应该将第一个参数中的参数扩展为printf。