36

How do I print a string with variables?

Trying this

awk -F ',' '{printf /p/${3}_abc/xyz/${5}_abc_def/}' file

Need this at output

/p/APPLE_abc/xyz/MANGO_abc_def/

where ${3} = APPLE and ${5} = MANGO

1
  • can you show file content ? Commented Oct 5, 2015 at 19:08

2 Answers 2

38

printf allows interpolation of variables. With this as the test file:

$ cat file
a,b,APPLE,d,MANGO,f

We can use printf to achieve the output you want as follows:

$ awk -F, '{printf "/p/%s_abc/xyz/%s_abc_def/\n",$3,$5;}' file
/p/APPLE_abc/xyz/MANGO_abc_def/

In printf, the string %s means insert-a-variable-here-as-a-string. We have two occurrences of %s, one for $3 and one for $5.

Sign up to request clarification or add additional context in comments.

Comments

21

Not as readable, but the printf isn't necessary here. Awk can insert the variables directly into the strings if you quote the string portion.

$ cat file.txt
1,2,APPLE,4,MANGO,6,7,8


$ awk -F, '{print "/p/" $3 "_abc/xyz/" $5 "_abc_def/"}' file.txt
/p/APPLE_abc/xyz/MANGO_abc_def/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.