Ubuntu – Help with Bash script – appending sequential numbers

bashcommand linescripts

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:

$ n=0
$ echo $((++n))
1
$ echo $((++n))
2
$ echo $((++n))
3

You can use printf %03d to format the result of $((++n)) as 001 002 003 and 010, 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:

function rename () {
  title="photo"
  n=0
  for file in *.jpeg; do
   printf -v new "$title-$1-$2_%03d.jpeg" "$((++n))"
   mv -v -- "$file" "$new"
  done
}

Which does:

$ rename birthday 2015
'file_001.jpeg' -> 'photo-birthday-2015_001.jpeg'
'file_002.jpeg' -> 'photo-birthday-2015_002.jpeg'
'file_003.jpeg' -> 'photo-birthday-2015_003.jpeg'

But there is already a useful rename command in Ubuntu, so you may want to use a different name :)

Related Question