Renaming a set of files to 001, 002, ... on Linux


I originally had a set of images of the form image_001.jpg, image_002.jpg, ...

I went through them and removed several. Now I'd like to rename the leftover files back to image_001.jpg, image_002.jpg, ...

Is there a Linux command that will do this neatly? I'm familiar with rename but can't see anything to order file names like this. I'm thinking that since ls *.jpg lists the files in order (with gaps), the solution would be to pass the output of that into a bash loop or something?

5/19/2009 12:38:29 AM

Accepted Answer

If I understand right, you have e.g. image_001.jpg, image_003.jpg, image_005.jpg, and you want to rename to image_001.jpg, image_002.jpg, image_003.jpg.

EDIT: This is modified to put the temp file in the current directory. As Stephan202 noted, this can make a significant difference if temp is on a different filesystem. To avoid hitting the temp file in the loop, it now goes through image*

i=1; temp=$(mktemp -p .); for file in image*
mv "$file" $temp;
mv $temp $(printf "image_%0.3d.jpg" $i)
i=$((i + 1))
5/19/2009 1:03:24 AM

A simple loop (test with echo, execute with mv):

for F in *; do
  echo "$F" `printf image_%03d.jpg $I`
  #mv "$F" `printf image_%03d.jpg $I` 2>/dev/null || true
  I=$((I + 1))

(I added 2>/dev/null || true to suppress warnings about identical source and target files. If this is not to your liking, go with Matthew Flaschen's answer.)

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow