Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 457
DisgruntledGoat Avatar asked May 19 '09 00:05

DisgruntledGoat


People also ask

How do I rename multiple files numerically?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.


2 Answers

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*
do
mv "$file" $temp;
mv $temp $(printf "image_%0.3d.jpg" $i)
i=$((i + 1))
done                                      
like image 84
Matthew Flaschen Avatar answered Nov 15 '22 12:11

Matthew Flaschen


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

I=1
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))
done

(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.)

like image 22
Stephan202 Avatar answered Nov 15 '22 13:11

Stephan202