Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

I want to rename a bunch of files which are called IMG0189.jpeg IMG0190.jpeg etc to something like IMG01.jpeg IMG02.jpeg etc respectively. Are there any way doing this using rename command? Or anything else? I tried reading the manual but it's very brief and doesn't give any idea about shifting numbers.

share|improve this question

1 Answer 1

up vote 4 down vote accepted

How about

ls > /tmp/list ; seq -w `ls | wc -l` | paste /tmp/list - | awk -F\\t '{ print $1, "IMG"$2".jpeg"}' | xargs -n2 mv
  • List the files and redirect the list to a temporary file /tmp/list
  • Write a sequence of numbers, padded with zeros, equal to the number of files to STDOUT
    • The file count is gotten by listing the files and piping to the wc (word count) app in "lines" mode
  • paste the sequence of numbers from the previous command onto the right side of the list of files from /tmp/list
    • Paste sticks two files together as columns separated by a TAB character
    • Pipe the output to the next program
  • Use a small awk program to reformat these two fields
    • Separators specified as tab (\t - the first slash is to escape the second one)
    • First field $1, the original file name printed as-is
    • Second field $2, the sequence number, printed with an IMG prefix and a .jpeg suffix
    • Pipe the output to the next program
  • Using xargs, pass the pairs of arguments to the mv (move / rename command)
    • -n2 means that it will pass 2 of them at a time

NB, this presumes that your original file names do not contain spaces.

If you want to start at a number other than 1, you need to manipulate the parameters of seq ; e.g.

COUNT=`ls | wc -l` ; FIRST=32 ; LAST=$(($FIRST + $COUNT)) ; seq -w $FIRST $LAST
share|improve this answer
    
Awesome, that exactly does what I want. And thanks so much for the great explanation. Is there any way that I can tell it to start numbering with for example 01 and then get to 10,11 etc? Also, I would like to know if I can start the numbering from an arbitrary number, for example from 32! –  Keivan Jun 17 '12 at 20:32
    
The "-w" parameter on seq makes it automatically pad to the required number of zeroes to hold the sequence you asked for, so that's already covered. See edit for starting at different number. –  Adrian Jun 18 '12 at 8:59
    
Thanks very much. You rock :) –  Keivan Jun 18 '12 at 16:06

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.