2

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.

K1.
  • 255

1 Answers1

5

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
Adrian
  • 5,216
  • 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! – K1. 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 08:59