remove double extensions in bash
Assuming:
- You only want to perform this in the current working directory (non-recursively)
- The double extensions have format precisely as
.jpg.jpg
:
Then the following script will work:
#!/bin/bashfor file in *.jpg.jpgdo mv "${file}" "${file%.jpg}"done
Explanation:
${file%.jpg}
: This part is called Parameter Subsitution.- From the same source: "${var%Pattern} Remove from $var the shortest part of $Pattern that matches the back end of $var."
- Note that the "pattern" mentioned here is called globbing, which is different from regular expression in important ways.
To use this script:
- Create a new file called
clean_de.sh
in that directory - Set it to executable by
chmod +x clean_de.sh
- Then run it by
./clean_de.sh
A Note of Warning:
As @gniourf_gniourf have pointed out, use the -n
option if your mv
supports it.
Otherwise - if you have a.jpg
and a.jpg.jpg
in the same directory, it will rename a.jpg.jpg
to a.jpg
and in the process override the already existing a.jpg
without warning.
Here is a more general, but still easy solution for this problem:
for oldName in `find . -name "*.*.*"`; do newName=`echo $oldName | rev | cut -f2- -d'.' | rev`; mv $oldName $newName; done
Short explanation:find . -name "*.*.*
- this will find only the files with duplicate extensions recursively
echo $oldName | rev | cut -f2- -d'.' | rev
- the trick happens here: the rev command do a reverse on the string, so you now you can see, that you want the whole filename from the first dot. (gpj.gpj.fdsa)
mv $oldName $newName
- to actually rename the files
Release Notes: since it is a simple one-line script, you can find unhandled cases. Files with an extra dot in the filename, super-deep directory structures, etc.