Replace column in one file with column from another 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.
  • While we are working with 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.
  • Once 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.
  • What this block does is it re-assigns second column value to array value by looking up the line number.
  • 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.