volingas
volingas

Reputation: 1173

printf behaves unexpectedly

I am having some surprising results at the bash prompt.

This is some data:

echo "version = blahblah" > xxx

And I want to do this:

printf "%s (%s)\n" `grep '^version =' xxx` "something"

Which I excpected to be:

version = blahblah (something)

Instead I get:

version (=)
blahblah (something)

Can somebody clarify why am I getting this?

Upvotes: 1

Views: 106

Answers (2)

anubhava
anubhava

Reputation: 785058

Use $(...) for command substitution and you must quote it:

printf "%s (%s)\n" "$(grep '^version =' xxx)" "something"

Without quoting printf sees space separated output from grep command as different parameters for printf.

BASH FAQ: Why is $(...) preferred over backticks?

Upvotes: 3

Inian
Inian

Reputation: 85560

Because the format specifiers don't match up with the one you defined and the number of arguments the printf sees. With

printf "%s (%s)\n" 
#      ^^^  ^^^    

the above, the command excepts two string sequences followed by a new-line character. But your arguments to printf() are more than that

version = blahblah something
# (1)  (2)   (3)    (4)

So printf() sees this mismatch between the specifiers and the arguments and inserts the newline after the 2nd argument which is =

printf '%s (%s)\n' 'version' '=' 'blahblah' 'something'

Since your expectation is to print the version = in one string, produce the entire grep output in one string as in anubhava's answer that way your printf sees the arguments as below

printf '%s (%s)\n' 'version = blahblah' 'something'

Upvotes: 2

Related Questions