繁体   English   中英

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

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

我正在尝试在 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 "%s\n" "$string"

printf(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()语法。 此外, string的范围也可能是使用它的函数的本地范围,所以我也改变了它。

输出:

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

我可以说“man printf”清楚地表明“%”字符必须通过另一个“%”进行转义,因此 printf“%%”导致单个“%”

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

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

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

 here\ is a\ few\\n tests

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM