在使用printf时如何在shell脚本中转义特殊字符? [英] While using printf how to escape special characters in shell script?
问题描述
我正在尝试在外壳中使用 printf
格式化字符串,我将从文件中获取输入字符串,该文件具有特殊字符,例如%,',",, \ user,\ tan
等.
I am trying to format a string with printf
in shell, i will get input string from a file , that have special characters like %,',"",,\user, \tan
etc.
如何转义输入字符串中的特殊字符?
How to escape the special characters that are in the input string ?
例如
#!/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;
我希望它会以我想要的格式打印
i am expecting this will print in the format i want like
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
也有问题.
So how can i get rid of the special characters while printing.? echo -e
also has the issue.
推荐答案
您可以使用 $''
将换行符和制表符括起来,然后使用简单的 echo
足够:
You can use $' '
to enclose the newlines and tab characters, then a plain echo
will suffice:
#!/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
的范围可能也仅限于使用它的函数,因此我也进行了更改.
I have also made a couple of other minor changes to your script. As well as making your FUNCTION_NAME lowercase, I have also used the more widely compatible function syntax. In this case, there's not a great deal of advantage (as $' '
strings are a bash extension anyway) but there's no reason to use the function func()
syntax as far as I'm aware. Also, the scope of string
may as well be local to the function in which it is used, so I changed that too.
输出:
The path to K:\Users\ca, this is good
The second line 123
It also has to be 100% nice than %99
这篇关于在使用printf时如何在shell脚本中转义特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!