0

I have more than 1 million images with name of

love-images-250x120.jpg
7788855441122-love-images-250x120.jpg
us-wallpapers33344.jpg
77441144desktop-wallpapers.jpg
desktop-wallpapers1144141411.jpg

I want to rename like this:

love-images.jpg
love-images-1.jpg
us-wallpapers.jpg
desktop-wallpapers.jpg
desktop-wallpapers-1.jpg

I am using this script:

for f in [0-9]*; do mv "$f" "`echo $f | -f sed 's/^[0-9]*\W*//'`"; done 

But this code stops when 2 images have same name. Is there any way to perform this action?

  • This is somewhat complicated for a Shell script. Don't use sed for this. Use Perl or Python. – shivams Dec 30 '18 at 11:03
  • 1
    askubuntu.com/questions/1105568/… – Thomas Dec 30 '18 at 11:18
  • 1
    @shivams A shell script can take you a long way :-) – ozzy Dec 30 '18 at 12:07
  • 1
    Perhaps if you can use some words to describe the transformations that you wish to occur, it would be clearer what you want to accomplish. – Jeff Schaller Dec 30 '18 at 17:46
0

This can be done using Python in the following manner:

#!/usr/bin/python

import glob
import re
import os
from collections import Counter

origNames = glob.glob('*jpg')

finalNames = []
for i in origNames:
    for old, new in [(r'\d+x\d+', ''), (r'\d', ''),(r'^\W+', ''),(r'-*\.-*', '.'), (r'\.jpg$', '')]:
        i = re.sub(old, new, i)
    finalNames.append(i)

counts = Counter(finalNames)
for s,num in counts.items():
    if num > 1:
        for suffix in range(1, num + 1):
            finalNames[finalNames.index(s)] = s + str(suffix)

print(origNames, finalNames)

for i,j in zip(origNames, finalNames):
    os.rename(i,j+".jpg")
  • @Shoabch Accept this answer if it worked for you. – shivams Jan 9 at 6:03
0

In Bash, the solution could look like this:

#!/bin/bash

shopt -s extglob

for fn_old in *.jpg; do

  i=0
  fn_new=${fn_old##+([-0-9])}                       # strip leading number sequence in basename 
  fn_new=${fn_new/%[-0-9]*([-0-9x]).jpg/.jpg}       # strip trailing number sequence in basename

  while [[ -e $fn_new ]]; do                        # see if proposed name already exists
    i=$((i+1))                                      # doublure counter
    fn_new=${fn_new/%*([-0-9]).jpg/-$i.jpg}         # try new filename with updated number
  done

  echo "$fn_old" -- "$fn_new"
  mv   "$fn_old" "$fn_new"

done

Be careful with the mv command. You may want to comment it out (or replace it with a cp) on a first run, just to see if the renaming scheme is what you want/expect.

For an explanation of the shell patterns and string manipulations, see: Bash pattern matching and Bash string manipulations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.