Sarath
Sarath

Reputation: 9156

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

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.

Upvotes: 15

Views: 31744

Answers (4)

Jonathan Mayer
Jonathan Mayer

Reputation: 1482

For the benefit of people who got here by clicking on the first search result after Googling "bash printf escaped", the %q formatter is used by printf to produce bash-escaped text.

For example:

$ printf "<<%q>>\n" 'foe fum' "fee fie"$'\n'
<<foe\ fum>>
<<$'fee fie\n'>>

From man printf:

%q     ARGUMENT is printed in a format that can be reused as shell
       input,  escaping  non-printable  characters with the 
       proposed POSIX $'' syntax.

Upvotes: 10

FIBA
FIBA

Reputation: 141

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

Upvotes: 10

Try

printf "%s\n" "$string"

See printf(1)

Upvotes: 14

Tom Fenech
Tom Fenech

Reputation: 74605

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

Upvotes: 3

Related Questions