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开发者_JAVA技巧 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?
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.
精彩评论