I am quite new to bash scripting and hoping that someone will help me out.
I have folders that include images named like so:
file_001.jpeg
file_002.jpeg
file_003.jpeg
I'm trying to write a bash function that takes two arguments and renames files like so:
photo-argument1-argument2_001.jpeg
e.g.
photo-christmas-2014_001.jpeg
Here's what I have:
function rename () {
title="photo"
h="-"
u="_"
new=$title$h$1$h$2$u
for file in *.jpeg; do
mv -v "$file" "$new"
done
}
so running rename birthday 2015
produces photo-birthday-2015_
,for example.
There's just one problem – how do I append numbers to the new filename? Either pulling out the existing numbers in the filename or generating new ones would be fine as far as results go, but which is the better/easier way, and how would I go about making this happen?
Best Answer
You can get bash to count for you just by telling it where to start, like this:
You can use
printf %03d
to format the result of$((++n))
as001
002
003
and010
,011
etc, for more accurate sorting. Also, there's no point setting-
and_
as variables since they are not going to vary. Your function could be like this:Which does:
But there is already a useful
rename
command in Ubuntu, so you may want to use a different name :)