xsong
xsong

Reputation: 33

bash printf backslash then new line

I am trying to create this from bash into a c header

#define XXXXX \

 "id title\n" \ 

 "1  developer\n" \

the script is 

FORMAT="  \"%-4s  %-32s\\\n"

printf "$FORMAT" "id" "title\\n\"" >> $FILE

printf "$FORMAT" "1" "Developer\\n\"" >> $FILE

the result would be

"id    title\n"                        \n  "1     Developer\n"                              \n

when I change FORMAT="%-4s %-32s \\ \n"

I get

"id    title\n"                           \ 
"1     Developer\n"                       \ 

and gcc start to complain the extra space after \

It seems that the \\ would be interpreted more than once if there is no space.

without using FORMAT="%-4s %-32s \\"

printf "$FORMAT" "id" "title\\n\"" >> $FILE

printf "\n" >> $FILE
...

Is there any better way to handle this?

Upvotes: 3

Views: 1347

Answers (2)

anubhava
anubhava

Reputation: 785098

shell treats double quote and single quote differently.

Don's use double quote here:

FORMAT="%-4s %-32s \\n"

Use single quote like this and avoid escaping:

FORMAT='%-4s %-32s \n'

OR for printing literal backslash and newline:

FORMAT='%-4s %-32s \\\n'

Upvotes: 0

Walker Mills
Walker Mills

Reputation: 56

Use hexadecimal escape sequences:

FORMAT="%-4s %-32s \x5C\n"

Upvotes: 3

Related Questions