views:

285

answers:

1

I am writing a shell script and I am stuck. The requirement is: I will receive files which have a sequence number on them like xyz0001abcd.DAT. I create a copy of that file, keeping the sequence number, as abcd000001gfh.DAT. The original filename uses four digits (up to 9999), and the copied one uses six (up to 999999).

I am stuck when 9999 comes in the original file. The original file sequence number will wrap around, but I want the copied file sequence number to continue. That is, after mapping 9999->009999, I will receive 0001 a second time, and map it to 10000 so that the copied file can continue with its numbering until 999999.

xyz0001abcd.DAT -> abcd000001gfh.DAT
xyz0002abcd.DAT -> abcd000002gfh.DAT
.
.
.
xyz9999abcd.DAT -> abcd009999gfh.DAT   # First sequence wraps around.
xyz0001abcd.DAT -> abcd010000gfh.DAT
xyz0002abcd.DAT -> abcd010001gfh.DAT

How could this be done in the form of a shell script? This would be very useful not only for me but for many others I suppose.

A: 

You can get the sequence number of your original file with:

echo $myFileName | sed 's/^[^0-9]*\(....\).*$/\1/'

You can get a list of all existing duplicate files named after your original file, but with a two digit prefix as you require with:

printf "%s\n" ` `echo $myFileName | sed "s/\([0-9]\)/??\1/" `

You can get the two digit prefix of a duplicate file with:

echo $myDupFileName | sed 's/^[^0-9]*\(..\).*$/\1/'

And the biggest two digit prefix of all duplicate files named after your original file by combining the two previous commands:

printf "%s\n" ` `echo $myFileName | sed "s/\([0-9]\)/??\1/" ` \
| tail -1 \
| sed 's/^[^0-9]*\(..\).*$/\1/'

I leave as an exercise:

  • the incrementation of this biggest prefix,
  • testing the case when no duplicate exists yet,
  • building a new name from all information already gathered.
mouviciel
well this could help me a bit.but the purpose is still not solved wherein i have to loop for 99 times since there are 99 cycles to come. like 0001-9999 is considered as one cycle and next start again 0001 which is considered as the second cycle.
Vijay Sarathi
My assumption is that you can identify the cycle by observing the filenames of existing duplicate files, which are numbered with that cycle.
mouviciel