Home > OS >  trying to replace file name with sed and for loop
trying to replace file name with sed and for loop

Time:01-01

I'm a total newbie, and I already spent 2 hours searching for answers, but I couldn't figure it on my own...

I only want to replace some filenames in a specific folder. I tried with sed and for loop.

The format I have for now is like:

IMG-20211228-WA0057.jpg
IMG-20211228-WA0069.jpg
IMG-20211228-WA0078.jpg

The result I want is :

image_1.jpg
image_2.jpg
image_3.jpg

How can I achieve that?

For now I've tried something like this:

for f in *.jpg; sed "s/^.*/image_${f}.jpg/"; done

Some help would be really kind.

CodePudding user response:

With bash. I assume that all images are in the current directory.

unset c; for i in *.jpg; do mv -iv "$i" "image_$((  c)).jpg"; done

Output:

renamed 'IMG-20211228-WA0057.jpg' -> 'image_1.jpg'
renamed 'IMG-20211228-WA0069.jpg' -> 'image_2.jpg'
renamed 'IMG-20211228-WA0078.jpg' -> 'image_3.jpg'

CodePudding user response:

An alternate technique, if you want to zero-pad the number (i.e. image-001 to image-999)

# 1. store the filenames in an array
images=(*.jpg)

# 2. width of the padding is the string length of the number of images
num=${#images[*]}
wid=${#num}

# 3. do the renaming
c=0
for img in "${images[@]}"; do
    printf -v newname 'image-%0*d.jpg' $wid $((  c))
    echo mv -iv "$img" "$newname"
done
  • Related