AWK How to replace a field using 2 shell variables?

Hello everybody:
I want to replace any field $2 of any file line (f.i. test.txt) matching $1 with a shell variable.

$ cat test.txt    
F       0
B       A
H       -12.33

Now I'm going to ask the value of variable B:

$ SEARCHVAR=B
$ OLDVAL=$(awk -v SEARCHVAR="$SEARCHVAR" '$1==SEARCHVAR {print $2}' test.txt)
$ echo $OLDVAL
A

And finally i tries to replace this value ("A") from field 2 by another shell variable with "10", using awk again:

$ NEWVAL=10
$ awk -v SEARCHVAR="$SEARCHVAR" OLDVAL="$OLDVAL" NEWVAL="$NEWVAL" '{if($1==SEARCHVAR && $2==OLDVAL) sub{OLDVAL,NEWVAL,$2} {print}}' test.txt

Unfortunately I only gets fatal error messages again & again.
Can you help me, please?
Thanks all in advace.

# cat file
F 0
B A
H -12.33
# awk -vSEARCHVAR="B" -vOLDVAL="A" -vNEWVAL=10 '$1==SEARCHVAR && $2==OLDVAL{sub(OLDVAL,NEWVAL,$2)}1' file
F 0
B 10
H -12.33

PS: Please use [code] tags when you post code or data sample.

1 Like

I just edited it with codes danmero.

Your solution was not able for me. I can't to look the old value from a file every time i needs to change it. I must that the shell do it by itself. But thanks to it, finally I found with the solution:

#!/bin/bash
SEARCHVAR=B
NEWVAL=10
OLDVAL=$(awk -v SEARCHVAR="$SEARCHVAR" '$1==SEARCHVAR {print $2}' test.txt)
awk -vSEARCHVAR="$SEARCHVAR" -vOLDVAL="$OLDVAL" -vNEWVAL="$NEWVAL" '$1==SEARCHVAR && $2==OLDVAL{sub(OLDVAL,NEWVAL,$2)}1' test.txt

the shell will show this:

A       0
B 10
C       -12.33

I hope this can to help it to someone :smiley:

# cat file
F       0
B       A
H       -12.33
# SEARCHVAR=B
# NEWVAL=10
# awk -vSEARCHVAR="$SEARCHVAR" -vNEWVAL="$NEWVAL" '$1==SEARCHVAR{$2=NEWVAL}1' OFS=\\t file
F       0
B       10
H       -12.33

If that's what you want , you don't need to parse the file twice.

1 Like

Oh yes!! That is an awsome solution. Thanks a lot ! :b: