Operating System - HP-UX
1752295 Members
5261 Online
108786 Solutions
New Discussion юеВ

Re: Numbering records with vi ( sequence number part of record )

 
SOLVED
Go to solution
yaron1
Advisor

Numbering records with vi ( sequence number part of record )

Hi,

I need to edit a file with data where the first 3 characters are the record sequence. I took out one record in the middle of the file. How can renumber the records to restore the correct sequence using the vi editor? Can vi do that or only awk? I dont mean going record by record and change it.

Thanks for the answers.
4 REPLIES 4
James R. Ferguson
Acclaimed Contributor

Re: Numbering records with vi ( sequence number part of record )

Hi:

If I understand your question correctly, no, 'vi' won't do the job. A possible 'awk' solution might look like:

# cat ./input
1 aaa
2 bbb
3 ccc
100 ddd
200 eee
300 fff

# awk '{printf "%3d%s\n",i++,substr($0,4)}' input
0 aaa
1 bbb
2 ccc
3 ddd
4 eee
5 fff

Regards!

...JRF...
Hein van den Heuvel
Honored Contributor
Solution

Re: Numbering records with vi ( sequence number part of record )

Should the sequence start at 1, or 001 ?

Or should there just not be gaps after the sequence number for the first record?

If you need a zero-filled sequence number just add a 0 in front of the d in the format for the solution James posted:

$ awk '{printf "%03d%s\n",NR,substr($0,4)}' input > output

One of many perl solutions could be:

$ perl -pe 's/.../sprintf("%03d",$.)/e' input

or with the number 'exposed' in a variable...

$ perl -pe '$n=sprintf("%03d",$.); s/.../$n/' input > output

and with 'in place' substitution:

perl -i -pe '$n=sprintf("%03d",$.); s/.../$n/' input


Cheers,
Hein

yaron1
Advisor

Re: Numbering records with vi ( sequence number part of record )

Hi

Yes, the sequence has to be 3 characters long, means zero filled on the left in values less than 100.

Thanks, have a nice weekend.
Dennis Handly
Acclaimed Contributor

Re: Numbering records with vi ( sequence number part of record )

Except for removing the old numbers, nl(1) is made for line numbering.