Passing space seprated variables in awk

Hi,

How to pass space seprated variables in awk. (HP-UX, sh shell)

I have the problem like below:

var="Hello"
var2="Manu Batham"
echo $var2 | awk -v variable=${var} '{ printf "%s %s", variable, $1}'

and its output is:
Hello Manu

while output should be:
Hello Manu Batham

Please help me to accept it spaces as well.

Thanks,
Manu

If you want to pass spaces on the command line, you should enclose the assignment in quotations, i.e.

awk -v "variable=${var}"

But actually your problem is the input read from stdin (by a pipe from echo). In this case, you are using $1. The default field separator is whitespace, so $2 will be "Batham". You change this with

awk -F','

for example to make it a comma. It can also be assigned by awk variable FS. If you want an entire input to become a single field, set the FS to something ridiculous.

[mute@geek ~]$ echo "Hello World" | awk '{print $1}' FS="something that never happens"
Hello World
2 Likes

That's great :smiley:

Not sure it's necessary, though. The entire, unmodified line is always available as $0 (unless you modify it yourself before!)

Hey neutronscott,

Your first option worked.

awk -v "variable=${var}"

I tried that before, but that time I was not putting it inside double quotes.

Thanks.

But yes, in OP's example $0 would be most easy solution. :wall:

My mind just read that he wanted spaces in a single field. :wink: