简体   繁体   中英

remove double extensions in bash

I am familiar with rename but I was curious does rename still apply for removing duplicate extensions??

Say I have a few files named:

  • picture2.jpg.jpg
  • picture9.jpg.jpg
  • picture3.jpg.jpg
  • picture6.jpg.jpg

How would you remove the the duplicate extension??

End result:

  • picture2.jpg
  • picture9.jpg
  • picture3.jpg
  • picture6.jpg

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/bash

for file in *.jpg.jpg
do
    mv "${file}" "${file%.jpg}"
done

Explanation:

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.

一行重命名命令也应该足够(至少对你的情况而言):

rename 's/\.jpg\.jpg$/.jpg/' *.jpg.jpg

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 "*.*.* find . -name "*.*.* - this will find only the files with duplicate extensions recursively

echo $oldName | rev | cut -f2- -d'.' | rev 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.

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