How can I generate a new name for a file if there's an existing file With that same name? In a Desktop environment a new name is generated my appending a number to the end of the file name, but how can this be accomplished from the command line?
I'm using the Android operating system with Busybox.
Best Answer
Assuming you have a POSIX shell, you can do this:
How to use this
This is a function so save it in your
~/.bashrc
and call it as you would the normalmv
.What this does
mv
executable in theMV
variableDEST
DEST
exists and is not a directory, this function assumes that your rename is trying to clobber a file.
, which marks the extension), the extension (anything after the final.
), the count (if any; anything in the prefix after the final-
).mv a.txt b.txt
it will first trymv a.txt b-001.txt
. This nextmv
call must also be the function itself because ifb-001.txt
also exists, we want to keep incrementing the counter until we find a new file name that doesn't exist.mv
executable is called with your original arguments.Caveats
foo-001.txt
, it will be moved tofoo-001-001.txt
.Notes
3
in theprintf
statement to whatever you like.