Reindex or re-increment last field of txt file.

I am using a database text file with a field that increments +1 with each new entry, occasionally if a entry is deleted the unique sequence is disrupted.

I am looking for a small script/function in sh and/or perl that would re index this.

Example of db file:

Name | Address | misc |number
Me|22 ave|another|1
you|33 rd|something|2
else|7|help|3
neighbor|22 long road||4

If a entry/record is deleted I might end up with this:

Name | Address | misc |number
Me|22 ave|another|1
you|33 rd|something|2
neighbor|22 long road||4

Which I would like to re-index to turn out like this:

Name | Address | misc |number
Me|22 ave|another|1
you|33 rd|something|2
neighbor|22 long road||3

Any help would rock.

Thankyou

Edit: To being with:
awk -F "|" '{print NR-1" "$NF}' filename.txt

Gives two parallel lines for comparison...

Almost there:
awk -F "|" '{$NF=NR-1; print NR-1 " " $NF}' filename.txt

Fixes it, now to figure out the substitue and put it in a nice perl function, which will be hard.

awk -F "|" -f file.awk filename

where, file.awk contains

NR!=1 {
for (i=1;i<=NF;i++)
{
 if(NF==i)
 {
  if( $NF != NR-1) printf("%d\n", NR-1); else printf("%s\n", $NF );
 }
 else
 {
  printf("%s|", $i);
 }
}
}

NR==1 { print $0 }

Perfect thank you :slight_smile:

Even took care of the first line which was just headers and no numbers.