[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Writing files with formatted name



On Fri, Feb 06, 2015 at 12:12:45PM -0500, Roman Gelfand wrote:
>    I need to write files with name format {5 digit sequential
>    number}.{extension I will supply}.
>    Is there a utility which would allow me to copy/move/put a file with the
>    above name format incrementing the sequence for each subsequent file. 
>    Something similar to what logrotate is doing.
>    Tlhanks in advance

Not tested, but this could work:

 #!/bin/bash

 # Start at zero
 sequencenumber=0

 # Extension is supplied to the script
 extension=$1

 # Working directory is second parameter, or CWD if not specified
 workingdir="${2:=.}/"

 # Use find to get the last number used
 # Find lists the files, tail gives us the last one, and the sed strips
 # the extension off it
 lastfile=$(find $workingdir -name *.$extension|tail -n 1|sed "s/\.${extension}$//")
 
 # New file is "lastfile" + 1
 newfile=$(( lastfile + 1 ))

 # Finally, echo out the new filename
 printf "${workingdir}%05d.$extension" $newfile

So, that lists a specified directory, adds one to the last file there
and prints out the new name. You'd use it like:

 $ mv someproblematic.file $(theabovescript.sh .log)

Or if you want to move to a different directory:

 $ mv someproblematic.file $(theabovescript.sh .log /path/to/foo)

NOTE that there is a race condition here. If, between calling "find" and
doing your "mv", the target file comes into existance, then you may
clobber it.

Attachment: signature.asc
Description: Digital signature


Reply to: