我正在尝试printf
在外壳中格式化字符串,我将从文件中获取输入字符串,这些字符串具有特殊字符,如%,',"",,\user, \tan
etc.
如何转义输入字符串中的特殊字符?
例如
#!/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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句