2014-09-21 93 views
4

我試圖格式化與外殼printf一個字符串,我會得到一個文件輸入字符串,有特殊字符,如%,',"",,\user, \tan使用printf如何在shell腳本中轉​​義特殊字符?

如何逃避特殊字符的輸入字符串?

#!/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也有問題。

+1

的''%中的一個參數是可能性就是爲什麼你不應該在第一個參數'printf'擴大的參數。 – chepner 2014-09-21 16:33:33

回答

2

您可以使用$' '圍住新行和製表符,那麼一個普通的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 
+0

this是我一直在尋找,謝謝 – Sarath 2014-09-21 13:51:53

5

嘗試

printf "%s\n" "$string" 

printf(1)

+0

它將打印'K:\ Users \ ca的路徑,這是很好的\ n第二行\ t123 \ n它也必須100%好於%99' – Sarath 2014-09-21 11:01:35

+0

需要\ n,\ t不是interperted – Sarath 2014-09-21 11:01:58