I have multiple files in a directory over 200 which I would like to rename by removing all other characters including the character and the rest after it appears twice.


One of the files in the directory is

Akouo - Float-H6hQuio26Ww.mp3

I would like a bash script which removes the second hyphen and all characters after it excluding the extension.

The end result should be

Akouo - Float.mp3
  • only bash? no python script? – Jacob Vlijm Oct 27 '14 at 6:22
  • @JacobVlijm Python is welcomed. Variety is good. – user271219 Oct 27 '14 at 14:52

To rename your example

Akouo - Float-H6hQuio26Ww.mp3


Akouo - Float.mp3


rename 's/-[^-]*\././' Akouo\ -\ Float-H6hQuio26Ww.mp3

If you want to rename all .mp3 files in your current directory with this schema, use

rename 's/-[^-]*\././' *-*-*.mp3

You can add option -n for a dry run.

  • If the file has 3+ hyphens in it, this will only remove from the last hyphen. You should consider using backreferences. – muru Oct 27 '14 at 14:58
  • @Cyrus Wow! Thank you very much. It worked. I am not too familiar with bash. I like explanations. Can you edit your question to include an explanation of your script? It'll be very helpful. – user271219 Oct 27 '14 at 14:59
  • Sorry, this is beyond the scope. As an introduction to Regex I would recommend this: proftpd.org/docs/howto/Regex.html – Cyrus Oct 27 '14 at 19:39

If we assume all files have two or more hypens and all files are mp3's, renaming (in python) would only take a few lines:

hyps = [i for i in range(len(name)) if name[i] == "-"]
name = name[:hyps[1]]+"mp3"

However, in my opinion, a script should (without explicit information that it is not necessary) take at least into account the possibility that the directory has sub-directories and/or contains:

  • hidden files
  • files with no extension
  • files with varying types of extensions
  • file names have only one, more then two or no hypens

so that:

Akouo - Float-H6hQuio26Ww.mp3


Akouo - Float.mp3

Then the script is a bit more extensive:

#!/usr/bin/env python3

import shutil
import os

sourcedir = "/path/to/files"

for root, dirs, files in os.walk(sourcedir):
    for name in files:
        if name.startswith(".") or name.count("-") < 2:
            if name.count(".") == 0:
                extension = ""
                extension = name[name.rfind("."):]
            hyps = [i for i in range(len(name)) if name[i] == "-"]
            newname = name[:hyps[1]].strip()+extension
            shutil.move(root+"/"+name, root+"/"+newname)

Copy the script into an empty file, set the path to your directory and save it as rename.py. Run it by the command:

python3 /path/to/rename.py
  • Awesome @Jacob. Thank you for this answer and elaboration. – user271219 Oct 27 '14 at 19:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy