Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove double extensions in bash

Tags:

bash

shell

rename

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
like image 343
DᴀʀᴛʜVᴀᴅᴇʀ Avatar asked Nov 23 '12 20:11

DᴀʀᴛʜVᴀᴅᴇʀ


People also ask

How do I remove extensions in bash?

Remove File Extension Using the basename Command in Bash If you know the name of the extension, then you can use the basename command to remove the extension from the filename. The first command-Line argument of the basename command is the variable's name, and the extension name is the second argument.

How do I remove multiple file extensions in Linux?

In Unix-like operating systems such as Linux, you can use the mv command to rename a single file or directory. To rename multiple files, you can use the rename utility. To rename files recursively across subdirectories, you can use the find and rename commands together.

What are double extensions?

The double extension method is used to obtain a price index from a representative sample of the items in stock. The index is calculated by measuring the inventory sample at its current-year and base-year costs and comparing the two figures.

How do I remove all file extensions?

All replies Open File Explorer and click View tab, Options. In Folder Options dialog, move to View tab, untick Hide extensions for known file types option, OK. Then you will se file's extension after its name, remove it.


1 Answers

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:

  • ${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.

like image 189
sampson-chen Avatar answered Oct 04 '22 13:10

sampson-chen