awk With multiple print variables

Hi,

I have a parameter which will be having the fields which needs to be filtered or derived. But This is not working which is mentioned below. I am using the below mentioned OS

uname -a
SunOS udora310 5.10 Generic_150400-11 sun4v sparc sun4v

param='$1$2'
nawk -v para="$param" 'BEGIN {FS="\037";OFS="\037"} {print para}' 1.dat > 2.dat

O/P:

$1$2
$1$2
$1$2
$1$2
$1$2

you cannot do it like this and there's no "eval" in awk.
Alternative:

param='1 2'
nawk -v para="$param" 'BEGIN {FS="\037";OFS="\037";n=split(para, paraA," ")} {for(i=1; i>=n;i++) printf("%s%s", $paraA, (i==n)?ORS:OFS)}' 1.dat > 2.dat

1 Like

Oh!! Actually, I was planning to write a generic function which may work for any number of fields to be seperated. So, Is it not possible?

You can't do it like that. $1$2 is just a plain string in para that won't be interpreted. You can try

nawk  'BEGIN {FS="\037";OFS="\037"} {print '$param'}' file

without the need for para , but this not the recommended solution. Other proposal:

nawk -v para="$param" 'BEGIN {FS="\037";OFS="\037"; split (para, P, "$")} {print $P[2]$P[3]}' file

Just use the approach I suggested - it's "number-of-fields" agnostic..

Hi RudiC,

Both the approach are working fine, But the OFS is not outputting in the file, not sure why its omitting the OFS.

Thanks

It's not in there, in neither proposal. Try print $P[2] OFS $P[3]

it should be in mine.

I believe, for making it more generic, I need to use the solution by vgersh99 with the for loop, which is with the below command

nawk -v para="$param" 'BEGIN {FS="\037";OFS="\037"; n=split (para, P, "$")} {for(i=1; i>=n;i++) printf("%s%s", $P, (i==n)?ORS:OFS)}' 1.dat,

But its doesn't O/P anything. Is it because of the solaris OS?

Most likely it's because this is not the suggested solution? Also we don't know what the '$param' looks like...

1 Like

Many thanks, This is working perfectly fine.

nawk -v para="$param" 'BEGIN {FS="\037";OFS="\037"; n=split (para, P, "$")} {for(i=2; i<=n;i++) printf("%s%s", $P, (i==n)?ORS:OFS)}' 1.dat

Regards,

---------- Post updated at 12:03 PM ---------- Previous update was at 12:02 PM ----------

Just not sure why the first number i should be equal to 2?, But it works

If your param='$1$2' and you n=split (para, P, "$") , then the P[1] is empty as the field preceding the FIRST $ , is empty.