Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Awk print string with variables

Tags:

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

like image 487
Glad Avatar asked Oct 05 '15 19:10

Glad


People also ask

How do I print text in awk?

To print a blank line, use print "" , where "" is the empty string. To print a fixed piece of text, use a string constant, such as "Don't Panic" , as one item. If you forget to use the double-quote characters, your text is taken as an awk expression, and you will probably get an error.

What is awk '{ print $1 }'?

If you notice awk 'print $1' prints first word of each line. If you use $3, it will print 3rd word of each line.

What is print $2?

awk '{ print $2; }' prints the second field of each line. This field happens to be the process ID from the ps aux output.


2 Answers

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.

like image 130
John1024 Avatar answered Sep 19 '22 17:09

John1024


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/
like image 30
zzevannn Avatar answered Sep 19 '22 17:09

zzevannn