Home > Blockchain >  Remove last parenthesized string in all file names in a directory
Remove last parenthesized string in all file names in a directory

Time:12-31

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.

CodePudding user response:

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.

CodePudding user response:

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.

CodePudding user response:

A version using zmv:

zmv -n '(*) \(*\).mp3' '$1.mp3'

With -n, this command lists what would change. Remove the -n to actually rename the files.

  • Related