简体   繁体   English

使用Linux Shell脚本重命名多个文件

[英]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. 我使用了以下shell脚本文件。

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? 那么,如何将COUNT值设置为10以获得我自己的输出?

The expr syntax is pretty outdated, POSIX shell allows you to do arithmetic evaluation with $(()) syntax. expr语法已经过时,POSIX shell允许您使用$(())语法进行算术评估。 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. 同样,由于注释中报告的错误,您似乎正在通过dash外壳运行它。 It does not seem to have all the features complying to the standard POSIX shell. 它似乎不具有符合标准POSIX shell的所有功能。 Run it with the sh or the bash shell. 使用shbash shell运行它。

And always use lowercase letters for user defined variables in your shell script. 并始终在Shell脚本中为用户定义的变量使用小写字母。 Upper case letters are primarily for the environment variables managed by the shell itself. 大写字母主要用于由Shell本身管理的环境变量。

With rename command you can suffix your files with Img_ : 使用重命名命令,您可以在文件后缀Img_

rename 's/^/Img_/' *

The ^ means replace the start of the filename with Img_ , ie: adds a suffix. ^表示将文件名的开头替换为Img_ ,即:添加后缀。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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