Skip to main content

Using Variable Int as positional arg [$($var) instead of $6] [Resolved]

I was working on an awk function to handle file translation and I did not expect to run into an issue with substitution.

Current code:

$ awk -F'|' '
    BEGIN{OFS = FS} 
    NR == FNR {a[$1 FS $2] = $3; next} 
    $8 FS $9 in a {$8 = a[$8 FS $9]} 
    1' File1 File2

So File1 is generated by me and will always only have 3 fields. But File2 can be one of several files, each of which would use a different argument number to access its data.

File2.a may have 20 arguments where arg 8 and 9 are the target values

File2.b may have 200 args where 4 and 159 are the target values

How can i handle this variability? I have tried ${$var}, ${!var}, echo $var, eval none of it seems to work

Desired code:

NR == FNR {a[$1 FS $2] = $3; next} 
    ${$var1} FS ${$var2} in a {${$var1} = a[${$var1} FS ${$var2}]} 

[Where var1 and var2 acts as parameter args for File2]
[var1 = ${16} and var2 = ${25}]

Additionally: Is there a limit to the number of parameter args that can be recognized? I've had conflicting responses. Like $9 is max, ${19} is max, 255, there is no limit its based off system specs...ect

Edit: I will attempt to clarify my question as best I can as requested in comments I am using awk to compare and replace arguments in a file. File1 will always have 3 arguments, The first 2 will correlate to args from File2. File2 will have an undetermined number of arguments. The mapping of the args between file1 and 2 will be handled by variable. As such I am trying to use a variable ($var1) in awk as a positional argument.

If I use:

$ awk -F'|' '
    BEGIN{OFS = FS} 
    NR == FNR {a[$1 FS $2] = $3; next} 
    $8 FS $9 in a {$8 = a[$8 FS $9]} 
    1' File1 File2

My code works.

If I use:

var1=9
$ awk -F'|' '
    BEGIN{OFS = FS} 
    NR == FNR {a[$1 FS $2] = $3; next} 
    $8 FS $var1 in a {$8 = a[$8 FS $var1]} 
    1' File1 File2

It no longer works

I have tried replacing $9 (in the awk) with ${$var1} / $(!var1) / $$var1

None of these have worked as expected For file architect please see my previous question


Question Credit: Gray_M
Question Reference
Asked October 9, 2019
Tags: awk
Posted Under: Unix Linux
9 views
2 Answers

To leave the answer for future searchers. Provided by pLumo and other commenters.

awk and bash treat '$' differently. You can use awk -v $var1=$input

-v is used to create variables. $var1 is the awk variable name. $input is the bash variable name. As mentioned by Issac they can even have the same names


credit: Gray_M
Answered October 9, 2019
Your Answer