Renaming bulk files with patterns and spaces on MacOSX El Capitan

I had a long list of video files with certain pattern on the name that I needed to remove, all the files had spaces on the name, so I used sed to work around this.

First a created a sed script with the pattern I wanted to remove and call it pattern.sed

s/(.*)(\s?\[[a-zA-Z0-9]{4,}\]\s?)(\.mkv)/\1\3/p

This makes 3 groups, the second group contains the pattern I want to remove, so this command prints the first and the third group to complete the name.

Now that I have the sed script with the pattern I need, I rename all the files with a loop.

for i in *.mkv
 do
 new_name=$(echo $i | sed -nEf pattern.sed)
 mv "$i" "$new_name"
 done

It’s important to double quote the variables in the mv command, otherwise mv will take each word of the name as an argument.

This only removes the pattern in your files, if you want to remove the spaces and change it with an underscore, which is recommended on any *NIX system.

for i in *\ *
 do
 mv "$i" "${i// /_}"
 done

the pattern in the for loop, matches all the files with spaces in the name, the substitution function (bash) can actually find and replace all the strings ${i//str/new_str}, but this doesn’t seem to work with extended regex, also note that it will replace any occurrence of the pattern on the string.

NOTE: To accomplish this on Linux just change the options in sed command;  “sed -nEf” to “sed -nrf“.

This entry was posted in MacOSX, regex, Sed, Unix and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*