How do I pass a stored value as the column number parameter to edit in awk?

Viewed 6792

I have a .dat file with | separator and I want to change the value of the column which is defined by a number passed as argument and stored in a var. My code is

awk -v var="$value" -F'|' '{ FS = OFS = "|" } $1=="$id" {$"\{$var}"=8}1'   
myfile.dat > tmp && mv tmp myfiletemp.dat

This changes the whole line to 8, obviously doesn't work. I was wondering what is the right way to write this part

{$"\{$var}"=8}1

For example, if I want to change the fourth column to 8 and I have value=4, how do I get {$4=8}?

3 Answers

Not only can you use a number in a variable by putting a $ in front of it, you can also use put a $ in front of an expression!

$ date | tee /dev/stderr | awk '{print $(2+2)}'
Mon Aug  3 12:47:39 CDT 2020
12:47:39
Related