Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding an Index field to a text file

Status
Not open for further replies.

btinder

Programmer
Mar 12, 2004
27
US
Hi there,

I have kludged together a KSH script to add an "index" field to a file, but it's extremely slow, because I'm reading each line of the file into a variable, then adding the index variable then the rest of the line.

This is how I did it:
while read buffer
do
index=`expr $index + 1`
echo "$index $buffer" >> NEWFILE
done < inputfile.txt

Is there a better way to do this? Thanks much!
 
Something like this ?
awk '{printf "%d %s\n",NR,$0}' inputfile.txt >NEWFILE

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
That will work.

The "index" field has to be 6 bytes, i.e. 000001

How do you format the NR variable in Awk?
 
Try this:
awk '{printf "%06d %s\n",NR,$0}' inputfile.txt >NEWFILE

Hope This Helps, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top