I have two files:
f1:
111 aaa 444
222 bbb 555
333 ccc 666
f2:
111 333 000 444
222 444 111 555
333 555 555 666
How can I replace second column in "f1", with third column from "f2" using awk?
try:
awk 'FNR==NR{a[NR]=$3;next}{$2=a[FNR]}1' f2 f1
Output:
111 000 444
222 111 555
333 555 666
Explanation of the above code:
FNR==NR
allows you to work with one entire file at a time. In this case it is the file f2
. NR
and FNR
both contain line numbers with the difference being FNR
gets reset to 1 when a new file is read where as NR
continues to increment. f2
file, we are creating an array called a
using line number (NR
) as the key
and third column ($3
) as the value. next
allows us to skip the rest of the action block. f2
file ends, we start to work on f1
file. NR==FNR
condition will not become false as FNR
will increment from 1 and NR
won't. So only second action block {$2=a[FNR]}
will be worked upon. 1
at the end prints the line. It returns true, and in awk
true statements results in printing of the line. f2 f1
is the order of files defined. Since we want to create an array from file f2
we put that first. If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With