Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove last parenthesized string in all file names in a directory

Tags:

bash

zsh

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:

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.

like image 608
Hoswoo Avatar asked Nov 16 '25 19:11

Hoswoo


2 Answers

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.

like image 74
konsolebox Avatar answered Nov 19 '25 09:11

konsolebox


This task can also be done by using pattern matching, rather than a regular expression:

for f in *\(*\).*; do mv -- "$f" "${f% \(*\).*}"."${f##*.}"; done

Note that this is not bash specific; it should work in any POSIX shell.

like image 35
M. Nejat Aydin Avatar answered Nov 19 '25 10:11

M. Nejat Aydin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!