Question

I am having trouble renaming image sequences in the shell.

I have about 300 files following the pattern myimage_001.jpg and I would like to transform that to myimage.0001.jpg where the numbers increment with each file.

This is what I have tried with no success (the -n flag being there to show the result before actually applying it):

rename -n 's/_/./g' *.jpg
Was it helpful?

Solution

Try this command :

rename _ . *.jpg

Example :

> touch myimage_001.jpg
-rw-r--r-- 1 oracle oinstall      0 Mar 17 10:55 myimage_001.jpg
> rename  _ . *.jpg
> ll
-rw-r--r-- 1 oracle oinstall      0 Mar 17 10:55 myimage.001.jpg

With an extra 0 :

> touch myimage_001.jpg
-rw-r--r-- 1 oracle oinstall      0 Mar 17 10:55 myimage_001.jpg
> rename  _ .0 *.jpg
> ll
-rw-r--r-- 1 oracle oinstall      0 Mar 17 10:55 myimage.0001.jpg

the syntax is simple :

rename 'old' 'new' 'data-source'

OTHER TIPS

Works fine for me? Note however that this does not add an additional leading zero like in your question, was this a typo?

$ find
.
./myimage_001.jpg
./myimage_007.jpg
./myimage_006.jpg
./myimage_002.jpg
./myimage_004.jpg
./myimage_009.jpg
./myimage_008.jpg
./myimage_003.jpg
./myimage_005.jpg

$ rename -n 's/_/./g' *.jpg
myimage_001.jpg renamed as myimage.001.jpg
myimage_002.jpg renamed as myimage.002.jpg
myimage_003.jpg renamed as myimage.003.jpg
myimage_004.jpg renamed as myimage.004.jpg
myimage_005.jpg renamed as myimage.005.jpg
myimage_006.jpg renamed as myimage.006.jpg
myimage_007.jpg renamed as myimage.007.jpg
myimage_008.jpg renamed as myimage.008.jpg
myimage_009.jpg renamed as myimage.009.jpg

$ rename 's/_/./g' *.jpg
$ find
.
./myimage.008.jpg
./myimage.007.jpg
./myimage.001.jpg
./myimage.003.jpg
./myimage.006.jpg
./myimage.005.jpg
./myimage.002.jpg
./myimage.009.jpg
./myimage.004.jpg

You can try something like:

for file in *.jpg; do 
    name="${file%_*}" 
    num="${file#*_}"
    num="${num%.*}"
    ext="${file#*.}"
    mv "$file" "$(printf "%s.%04d.%s" $name $num $ext)"
done

This gives:

$ ls
myimage_001.jpg  myimage_002.jpg

$ for file in *.jpg; do 
  name="${file%_*}" 
  num="${file#*_}"
  num="${num%.*}"
  ext="${file#*.}"
  mv "$file" "$(printf "%s.%04d.%s" $name $num $ext)"
done

$ ls
myimage.0001.jpg  myimage.0002.jpg

Another alternative:

$ touch a.txt  b.txt  c.txt  d.txt  e.txt  f.txt
$ ls
a.txt  b.txt  c.txt  d.txt  e.txt  f.txt

We can use ls combined with sed + xargs to achieve your goal.

$ ls | sed -e "p;s/\.txt$/\.sql/"|xargs -n2 mv

$ ls
a.sql  b.sql  c.sql  d.sql  e.sql  f.sql

See http://nixtip.wordpress.com/2010/10/20/using-xargs-to-rename-multiple-files/ for detailed information.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top