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}
?
$
in front of it turns it in to a reference to the column. So i=3; print $i; print i
will print the third column and then the number 3.bash
variables inside your awk
code, which either won't work (with single-quoted code) or be very messy.-F
option specifies FS
for you, so using that and setting it in your code is redundant.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