简体   繁体   中英

Multiple files rename using linux shell script

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?

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.

With rename command you can suffix your files with Img_ :

rename 's/^/Img_/' *

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM