Reputation: 133
I have file like
A 1 2
A 1
A 1
B 2 3
B 2
B 2
I would like to copy the 2 in all A 1. I.e if($1="A" && $2==1) print value that is $3. I have tried like using awk but not able to get the result.
The result could be
A 1 2
A 1 2
A 1 2
B 2 3
B 2 3
B 2 3
Thanking you in advance
Upvotes: 0
Views: 78
Reputation: 5072
Try awk '{$3 == ""{print $0, var; next} {var=$3; print}' myfile
Note that this works only for your format, and only if at least the 1st line of your file has a 3rd column
As I didn't know wether validation was crucial for your script, this doesn't check for validity of 2nd field (i.e. this will append 2
even if you have A 5
), nor does it check the 1st one (i.e., having a file like this :
A 1 2
B 2
will output
A 1 2
B 2 2
However, if you use it with files formated like the one you showed as an example, it will work exactly as you want. This will even work if you add
C 3 4
C 3
...
Upvotes: 0
Reputation: 41460
Here is a small awk
that should do:
awk '$3!="" {t=$3} {$3=t} 1'
A 1 2
A 1 2
A 1 2
B 2 3
B 2 3
B 2 3
Or this:
awk '$3 || $3=="0" {t=$3} {$3=t} 1' file
Upvotes: 1
Reputation: 195159
based on the example and your codes, this may help you:
awk 'NF==3{a[$1,$2]=$3}NF<3{$3=a[$1,$2]}7' file
Upvotes: 2