Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove last parenthesized string in all file names in a directory

I have many song files that I am trying to rename. I am trying to remove the last occurrence of a parenthesized string in all of the song file names. For example, they are formatted like this: song - artist (foo) (bar) (text I want to remove).mp3, but I want the output to be song - artist (foo) (bar).mp3.

Currently, I have found a zsh command that can delete all parenthesized strings as seen in an answer to this post Renaming files to remove parenthesized strings.

The solution from that post that almost worked for me was to use this command:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

autoload zmv # best in ~/.zshrc
zmv -n '*' '${f//[[:space:]]#[(]*[)]}'

However, this removes all parenthesized strings in all the file names. I am only trying to remove the last occurrence of parenthesized strings in the file names.

>Solution :

You can use Bash’s greedy regex:

#!/bin/bash

re='(.*)(\([^)]*\))(.*)'

for file in *; do
    if [[ $file =~ $re ]]; then
        echo mv -i -- "$file" "${BASH_REMATCH[1]}${BASH_REMATCH[3]-}"
    fi
done

Filename expansion needs to be improved however.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading