1

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

1 Answer 1

3

How about

awk '
  BEGIN{n=0}
  NR==FNR && a[$2]=="" {
    a[$2]=n++
  }
  {
    $2=a[$2]; print $0 > "new"FILENAME
  }' file1.txt file2.txt
2
  • Why the BEGIN block? The first n++ should set it to 1, there's no reason AFAIK to initialize it first.
    – terdon
    Apr 2, 2016 at 14:04
  • @terdon dunno - I wasn't trying to golf it, I included it really just for anyone wanting to adjust the start index Apr 2, 2016 at 15:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .