Ubuntu – Replace text in one file and match in second file

bashcommand linetext processing

I have two text files, file1 and file2. In file1, I would like to start the numbering in the second column (after the space) from 0. However, this new numbering should match the numbering in file2.

file1.txt

b/boat_deck/19405.jpg 19
b/boat_deck/19491.jpg 19
c/church_outdoor/32697.jpg 325
c/church_outdoor/32110.jpg 325
c/courtyard/42770.jpg 42
c/courtyard/42654.jpg 42

file2.txt

val/00000533.jpg 325
val/00000378.jpg 19
val/00000524.jpg 42

Desired output with new numbering. As you can see in newfile1, 19 got replaced by 0, 325 by 1, and 42 by 2. Likewise, in newfile2, the numbers in the second column correspond with the new numbering (from newfile1).

newfile1.txt

b/boat_deck/19405.jpg 0
b/boat_deck/19491.jpg 0
c/church_outdoor/32697.jpg 1
c/church_outdoor/32110.jpg 1
c/courtyard/42770.jpg 2
c/courtyard/42654.jpg 2

newfile2.txt

val/00000533.jpg 1
val/00000378.jpg 0
val/00000524.jpg 2

Best Answer

How about

awk '
  BEGIN{n=0}
  NR==FNR && a[$2]=="" {
    a[$2]=n++
  }
  {
    $2=a[$2]; print $0 > "new"FILENAME
  }' file1.txt file2.txt