On Wed, Jun 11, 2008, Dan Bar Dov wrote about "Help with printf":
>...
> But if I put the format in a variable (as opposed to a string literal), I
> find that
> escape processing does not occur.
>...
> and running (# is the prompt)
> # ./test "%s flowers\n" 7
>
> give the output
> 7 flowers\n#
What you call "escape processing", i.e., the conversion of the two characters
"\n" into one newline character (ASCII code 10), isn't done by the printf
library function - rather it is done by the C compiler!
When the C compiler sees the character \ followed by n inside a string
constant, it translates it into a newline character.
The shell does not normally do this translation, which is why your "test"
program gets the characters \ and n, not a newline.
There are several ways you can fix this problem. The most obvious one is
to parse the string in the C code, and do the replacement of \n into a
newline yourself. Another option is to have "echo" (sometimes a shell builtin,
sometimes an external program) do the replacement for you, as in:
./test `echo -n "%s flowers\n"` 7
Finally, if your intent is to write a printf-like tool for the shell, you
can just use the "printf" tool that comes from GNU's coreutils, that already
does its own backslash transformations. For example:
$ printf "1+1=%5d\n" 2
1+1= 2
By the way, you can look at coreutil's printf code to see how it does the
backslash transformations (isn't free software great?)
--
Nadav Har'El | Wednesday, Jun 11 2008, 8 Sivan 5768
[EMAIL PROTECTED] |-----------------------------------------
Phone +972-523-790466, ICQ 13349191 |If you lost your left arm, your right arm
http://nadav.harel.org.il |would be left.
=================================================================
To unsubscribe, send mail to [EMAIL PROTECTED] with
the word "unsubscribe" in the message body, e.g., run the command
echo unsubscribe | mail [EMAIL PROTECTED]