SoFunction
Updated on 2025-03-09

Detailed explanation of the example of batch processing of image file names on the Shell command line

Shell command line batch processing image file names

Preface:

Downloaded a bunch of pictures from the Internet, some of which are *.jpg, and some of which are *.jpeg. And the file names are long and short, which is very bad. Therefore, I want to organize all these files, of course I will use a shell to process them!

Do it as soon as you say it.

Loop all files

First, I put all the messy pictures under the ./image/ folder.

Then write a shell file on the outer layer and enter the following content.

My file structure is demonstrated as follows:


document
image/
image/
for f in $(find ./image -iname "*.*"); do
 echo $f
done

Then execute the sh command and successfully output all picture files on the command line.

Implement i++ digital effects

I want to name all pictures as such image files, so I need an i++ effect similar to js.

So, modify the above code to

# Make an i variablei=1
for f in $(find ./image -iname "*.*"); do
 ## Print i echo $i
 echo $f
 ## Calculate i++ ((i++))
done

OK, the numbers have been output smoothly. At this point, we obviously got what we wanted. Just copy the file.

Realize the renaming effect

# Make an i variablei=1
mkdir img
for f in $(find ./image -iname "*.*"); do
 cp $f ./img/$
 ## Calculate i++ ((i++))
done

OK, as above, we will rename all the images according to the numbers and put them in a new img folder. The effect we want is achieved.

Name the picture with MD5 value

Suddenly I thought that numbers are not reliable. If you accidentally execute them next time, it is easy to mess up the picture. The MD5 value is reliable, and be careful, you can also filter the same picture.

Well, ideals are full, let’s take a look.

md5 -q $file

The MD5 calculated value of the file can be output. Just use this. Reform the above code as follows:

mkdir img
for f in $(find ./image -iname "*.*"); do
 # Calculate the MD5 value and assign a variable a=$(md5 -q $f)
 # Copy the file cp $f ./img/$
done

I want to use this bunch of files to implement it repeatedly, so I use copy. If I don’t need to consider this, I can completely rename it using mv. The code is as follows:

mkdir img
for f in $(find ./image -iname "*.*"); do
 # Calculate the MD5 value and assign a variable a=$(md5 -q $f)
 # Copy the file mv $f ./image/$
done

All the above commands are run based on the MAC system. There may be slight differences if it is Linux.

If you have any questions, please leave a message or go to the community of this site to exchange and discuss. Thank you for reading. I hope it can help you. Thank you for your support for this site!