2

I have following images.

10.jpg
11.jpg
12.jpg

I want to remove above images. I used following shell script file.

for file in /home/scrapping/imgs/*
do
    COUNT=$(expr $COUNT + 1)
    STRING="/home/scrapping/imgs/""Img_"$COUNT".jpg"
    echo $STRING
    mv "$file" "$STRING"
done

So, replaced file name

Img_1.jpg
Img_2.jpg
Img_3.jpg

But, I want to replace the file name like this:

Img_10.jpg
Img_11.jpg
Img_12.jpg

So, How to set COUNT value 10 to get my own output?

4
  • Pre-assign 10 to the count? Commented Dec 29, 2017 at 7:23
  • Initialize the variable count before for Commented Dec 29, 2017 at 7:28
  • @ValdeirPsr I have initialized but not working. Commented Dec 29, 2017 at 7:33
  • Possible duplicate of Rename all files in a folder with a prefix in a single unix command Commented Dec 29, 2017 at 12:49

2 Answers 2

4

The expr syntax is pretty outdated, POSIX shell allows you to do arithmetic evaluation with $(()) syntax. You can just do

#!/usr/bin/env bash

count=10
for file in /home/scrapping/imgs/*; do
    [ -f "$file" ] || continue
    mv "$file" "/home/scrapping/imgs/Img_$((count++)).jpg"
done

Also from the errors reported in the comments, you seem to be running it from the dash shell. It does not seem to have all the features complying to the standard POSIX shell. Run it with the sh or the bash shell.

And always use lowercase letters for user defined variables in your shell script. Upper case letters are primarily for the environment variables managed by the shell itself.

Sign up to request clarification or add additional context in comments.

Comments

1

With rename command you can suffix your files with Img_:

rename 's/^/Img_/' *

The ^ means replace the start of the filename with Img_, i.e: adds a suffix.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.