Simple script
#!/bin/bash
for file in ~/path/to/images/*; do
TYPE=$(file --mime-type -b "$file" | cut -f2 -d/);
if [[ ! $file =~ \.$TYPE ]]; then
echo mv -v "$file" "$file.$TYPE";
fi
done
Explanation of TYPE=$(file --mime-type -b "$file" | cut -f2 -d/);
(finding file type)
find the extension of each $file
using file
(determine file type) command.
--mime-type, --mime-encoding
option used for print only the specified element(s).
-b, --brief
option used for do not prepend filenames to output lines (brief mode).
See also man file for more info.
Now we extracted the file type and saved it into TYPE
variable.
And what is cut -f2 -d/
command? This used for printing just extension type, Like png
in image/png
output from file --mime-type -b "$file"
result.
-f2
prints second part with /
delimiter(-d
option) between fields. ex: Print png
in image/png
.
See also man cut for more info.
Explanation of if [[...]];
(checking file extension)
We skipped all existing extension with a simple regex, using the =~
operator inside a [[...]]
test in if condition:
if [[ $file =~ \.$TYPE ]];
While $file
is your images filenames and $TYPE
is its extension which we found and stored that into TYPE
variable in TYPE=$(file --mime-type -b "$file" | cut -f2 -d/);
.
Then we skip to rename all files that has an extension with themselves.
!
refer to: if file has NO extension with itself, then rename that and add its extension at the end of its name.
Explanation of echo mv -v "$file" "$file.$TYPE";
(rename step)
In this line Actually we are appending the file extension(if $file
doesn't an extension with itself) at the end of $file
file by using mv
command. mv
also using for renaming Files/Directory.
Then we rename $file
to $file.$TYPE
. For example file 1
will be rename to 1.png
if its file type was png
format.
in theory actually above mv command do this: rename filename -> filename.filetype
That filename stored into $file
variable and filetype stored into $TYPE
variable.
How can you use this script?
Copy and paste the script in gedit
and save it with your favorite name ex: batchRename
, then open Terminal and run it by the following command:
bash batchRename
DON'T forget before running script verify your correct images path /path/to/images/
and for renaming on your files after checking the result with echo
command, remove echo
from the beginning echo mv -v "$file" "$file.$TYPE"
and run the script again and enjoy renaming ;)