-1

I have a directory full of files named

image_1.jpg
image_2.jpg
...
image_10.jpg
...
image_335.jpg

Now I want to use a command line tool which expects the images to be alphabetical ordered. But the alphabetical order of these filenames is: image_100.jpg image_101.jpg ... image_10.jpg image_11.jpg ... image_1.jpg ....

How can I rename these files using a short shell / bash command? I've found that sed is possible a way to go, but this tool is a mystery to me.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sweiler
  • 397
  • 1
  • 3
  • 7

2 Answers2

2

With bash:

for i in *; do if [[ $i =~ (image_)([0-9]{1,2})(\.jpg) ]]; then printf -v num "%03d" "${BASH_REMATCH[2]}"; echo mv -v "$i" "${BASH_REMATCH[1]}${num}${BASH_REMATCH[3]}"; fi; done

If everything looks okay, remove echo.

Tested with a directory with those file names:

image_100.jpg
image_101.jpg
image_10.jpg
image_11.jpg
image_1.jpg
image_2.jpg
image_334.jpg
image_335.jpg
image_3.jpg

The created commands:

mv -v image_10.jpg image_010.jpg
mv -v image_11.jpg image_011.jpg
mv -v image_1.jpg image_001.jpg
mv -v image_2.jpg image_002.jpg
mv -v image_3.jpg image_003.jpg

Result:

image_001.jpg
image_002.jpg
image_003.jpg
image_010.jpg
image_011.jpg
image_100.jpg
image_101.jpg
image_334.jpg
image_335.jpg
Cyrus
  • 84,225
  • 14
  • 89
  • 153
0

Ok I've found a solution, not using a shell command but by writing a simple ruby script:

input = Dir.glob("image*.jpg")

input.each do |name|
  parts = name.split /[_\.]/
  number = parts[1]
  number = number.rjust(3, '0')
  new_name = [parts[0], '_', number, '.', parts[2]].join
  File.rename(name, new_name)
end
sweiler
  • 397
  • 1
  • 3
  • 7