Gregg's MOTD

Tips & Tricks that I've Encountered Over the Years...

Remove Parentheses from File Names

September 20, 2023 — Gregg Szumowski

This script will rename Windows backup files by removing the ’ (date)’ from the filename. It will remove the parentheses and everything between them from the file name, so that a file with the name file-1 (2023-09-10).txt will be renamed to file-1.txt. Note that since the data between the parentheses will be removed, the resulting file name must be unique for this script to prevent data from being overwritten. Other than that it should work for any fileset that meets the beforementioned constraints.

First, let’s create some sample files:

$ for i in {0..9}; do touch "file-${i} (number-${i}).txt"; done
$ ls
file-0\ (number-0).txt file-4\ (number-4).txt file-8\ (number-8).txt
file-1\ (number-1).txt file-5\ (number-5).txt file-9\ (number-9).txt
file-2\ (number-2).txt file-6\ (number-6).txt
file-3\ (number-3).txt file-7\ (number-7).txt

Now, we’ll execute the script on the sample files:

$ for f in *; do n=$(echo $f | sed "s/[ (][^)]*[)]//g");mv "${f}" "${n}"; done

If we look at the directory listing now we see that the file names are updated:

$ ls
file-0.txt file-2.txt file-4.txt file-6.txt file-8.txt
file-1.txt file-3.txt file-5.txt file-7.txt file-9.txt

Tags: cli, bash, rename, motd