In your second version, e.g.
awk -i inplace '{if($1==$A) {$2=$B} print $0}' myfile.txt
$A
and $B
are awk
variables, not shell variables. Note how the awk
script is run between single-quotes -- shell variable expansion does not occur. So awk
sees $A
which it has no value for and simply initializes the variable as 0
.
In awk
, you can either pass variable values with the -v
option or use the BEGIN{ ... }
rule to do it. Since you are wanting to use shell variables per-your comment, you will need to use the -v
form, e.g.
awk -v A="AABBCC" -v B=30 -i inplace '{if($1==$A) {$2=$B} print $0}' myfile.txt
(note: using $A
with AABBCC
would make no sense as it wouldn't correspond to a valid field in your input, but using just A
could. Now with B=30
, that may correspond to the 30th field, but if you have less than 30 fields, then it would be B
and not $B
-- the $
prefix in awk
indicating the value of the variable corresponds to a specific field of input -- for which you want its value)
Now awk
knows what A
is and what B
is.