【问题标题】:While using printf how to escape special characters in shell script?使用 printf 时如何转义 shell 脚本中的特殊字符?
【发布时间】: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

标签: linux bash shell printf


【解决方案1】:

试试

printf "%s\n" "$string"

printf(1)

【讨论】:

  • 它将打印The path to K:\Users\ca, this is good\nThe second line\t123\nIt also has to be 100% nice than %99
  • 需要\n,\t不插手
  • 在某些情况下这是一个非常干净的解决方案
【解决方案2】:

为了方便大家在谷歌搜索“bash printf escaped”后点击第一个搜索结果,使用printf生成bash-escaped文本的正确方法是:

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

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

 here\ is a\ few\\n tests

【讨论】:

    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      我可以说“man printf”清楚地表明一个“%”字符必须通过另一个“%”来转义 所以 printf "%%" 结果是一个 "%"

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-30
        • 1970-01-01
        • 2013-11-18
        • 2013-12-23
        • 1970-01-01
        相关资源
        最近更新 更多