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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25958430/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:23:14  来源:igfitidea点击:

While using printf how to escape special characters in shell script?

linuxbashshellprintf

提问by Sarath

I am trying to format a string with printfin shell, i will get input string from a file , that have special characters like %,',"",,\user, \tanetc.

我正在尝试printf在 shell 中格式化字符串,我将从文件中获取输入字符串,该文件具有诸如%,',"",,\user, \tan等特殊字符。

How to escape the special characters that are in the input string ?

如何转义输入字符串中的特殊字符?

Eg

例如

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

But its giving unexpected out puts

但它给出了意想不到的输出

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

So how can i get rid of the special characters while printing.? echo -ealso has the issue.

那么如何在打印时摆脱特殊字符。?echo -e也有问题。

采纳答案by Tom Fenech

You can use $' 'to enclose the newlines and tab characters, then a plain echowill suffice:

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

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 stringmay as well be local to the function in which it is used, so I changed that too.

我还对您的脚本进行了其他一些小改动。除了使您的 FUNCTION_NAME 小写外,我还使用了更广泛兼容的函数语法。在这种情况下,没有太多优势(因为$' '字符串无论如何都是 bash 扩展)但function func()据我所知没有理由使用该语法。此外,范围string也可能是使用它的函数的本地范围,所以我也改变了它。

Output:

输出:

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

回答by Basile Starynkevitch

Try

尝试

printf "%s\n" "$string"

See printf(1)

printf(1)