Friday, March 14, 2014

Appending Sequential Numbers To A Word Or File Using Linux

I needed to append some sequential numbering to a word to use in a list. For example :

word01
word02
word03
word04

The sequence of numbers had to go from 1 - 4999. Now I could of wrote this out 4999 times but that would of been painfully boring and probably would of given me a terrible case of carpal tunnel by the end of it all. Plus I use Linux, there must be an easier way to do this and there is ! It's called seq

If  you open up the terminal of your choice and type man seq it pulls up a small man page with a few options you can use. The option were interested in is the -f option. This is the printf style floating-point FORMAT. If your interested in getting a better understanding of this click here. Here's a basic command using this format with output:

seq -f "%04g" 6

output:

0001
0002
0003
0004
0005
0006


 The "%04g" gives us 4 digits starting with 0001 and continues on to 0006. This is pretty basic. We need to append these numbers to a word now, and start with 01 and go up to 4999. Heres what we do :

seq -f "yourword%02g" 4999

output:

yourword01
yourword02
yourword03


And this goes on till it reaches yourword4999. That would of been a lot of typing.

So now we need to put all this into a text file for another program to reference. Here's what you do.

seq -f "yourword%02g" 4999 > reference_file.txt

By adding the greater than symbol it pipes the output to a text file.

You can name the text file whatever you want. For my purposes it was a list file for another program I was running. Each word pointed the program to a numbered dir on a computer. You could also use this to create sequential file names.  For example:

touch $(seq -f "yourfilename%02g.txt" 10)
 
This would create yourfilename01.txt to yourfilename10.txt.  

 This is a great little program and with a little imagination you could really put this program to great use.   

No comments:

Post a Comment