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

18,795

Solution 1

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

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.

Output:

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

Solution 2

Try

printf "%s\n" "$string"

See printf(1)

Solution 3

May I remark that "man printf" shows clearly that a "%" character has to escaped by means of another "%" so printf "%%" results in a single "%"

Solution 4

For the benefit of people who got here by clicking on the first search result after Googling "bash printf escaped", the correct way to use printf to generate bash-escaped text is:

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

Which outputs (without a trailing newline):

 here\ is a\ few\\n tests
Share:
18,795
Sarath
Author by

Sarath

JavaScript :) :) :)

Updated on July 23, 2022

Comments

  • Sarath
    Sarath almost 2 years

    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 ?

    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 -e also has the issue.