pmdaly
pmdaly

Reputation: 1202

Remove all additional extensions from files

I have files that have any number of extensions

a.jpg
b.jpg.jpg
c.jpg.jpg.png
...

I need to remove all extensions beyond the first one

a.jpg
b.jpg
c.jpg
... 

I currently have the following to find files with additional extensions

find . -type f -name "*.*.*"
find . -type f -name "*.*.*.*"
find . -type f -name "*.*.*.*.*"
...

I'm not sure how to make a cleaner version of this. The only periods in the file names are right before the extensions so I can pick everything up to and including the first extension with regex along with -exec mv in the above find command but I'm not sure how to do this.

Upvotes: 0

Views: 93

Answers (2)

PesaThe
PesaThe

Reputation: 7499

Using only parameter expansion with extglob:

#!/usr/bin/env bash

shopt -s extglob

for file in *.*.*; do
    del=${file##+([^.]).+([^.])}
    mv "$file" "${file%"$del"}"
done

Upvotes: 0

anubhava
anubhava

Reputation: 784938

If you have rename utility then you can use:

rename -n 's/([^.]*\.[^.]+).+/$1/' *.*.*

Remove -n (dry run) after you are satisfied with output.

If you don't have rename then you may use sed like this:

for i in *.*.*; do
    echo mv "$i" "$(sed -E 's/([^.]*\.[^.]+).+/\1/' <<< "$i")"
done

Remove echo after you're satisfied with the output.

Upvotes: 1

Related Questions