Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace column in one file with column from another using awk?

Tags:

replace

awk

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?

like image 557
kofucii Avatar asked Oct 21 '11 07:10

kofucii


1 Answers

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.
like image 145
Chris Avatar answered Oct 25 '22 05:10

Chris