bashawkparameter-passingsh

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


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}?


Solution

  • Here's how I would do this:

    #!/bin/bash
    column=4
    value=8
    id=1
    awk -v col="$column" -v val="$value" -v id="$id" '
        BEGIN {FS=OFS="|"}
        $1==id {$col=val}
        print
    ' myfile.dat > myfiletemp.dat
    

    Given this input:

    1|34|test|should be 8|8583|foo
    2|68|test|should be left alone|5828|bar
    3|61|test|should be left alone|6682|baz
    

    This is the output:

    1|34|test|8|8583|foo
    2|68|test|should be left alone|5828|bar
    3|61|test|should be left alone|6682|baz