Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sed error "\1 not defined in the RE" on MacOSX 10.9.5

I am trying to build a generic formatter for my MP3 file names (very important) with bash, and a large part of this is being able to move text around using regex variables. For example I am trying to remove the parentheses () from around the ft. Kevin Parker.

oldfilename="Mark Ronson - 02 Summer Breaking (ft. Kevin Parker).mp3"

newfilename=$(echo $oldfilename | sed -E "s/ft.\(*\)/ft.\1/g")

This causes the error:

sed: 1: "s/ft.\(*\)/gt.\1/g": \1 not defined in the RE

I have tried escaping and not escaping the (), and adding and removing the -E switch as recommended by .bash_profile sed: \1 not defined in the RE. Help?!

like image 995
mummybot Avatar asked Jan 21 '15 16:01

mummybot


1 Answers

If you use -E, then \( and \) are actual parentheses; to capture, you'd use just ( and ). Here, you want to remove parentheses, so you need to match a literal (, capture the content up to the next ) and match but not capture the close ), and replace the whole lot with just the capture:

newfilename=$(echo "$oldfilename" | sed -E "s/\((ft[^)]*)\)/\1/g")

Or, for amusement value, you can do it without -E:

newfilename=$(echo "$oldfilename" | sed -e "s/(\(ft[^)]*\))/\1/g")

(The -e is a cheat; it just identifies an expression that's part of the sed script. It does not mean 'opposite of -E' and you could have both -E and one or more -e …arg… argument pairs.)

Note that the file name should be in quotes unless you are deliberately ensuring that any leading or trailing blanks are removed, and any internal tabs or newlines are replaced with blanks, and any multiple blanks in the name are replaced with a single tab. If you do want the 'space normalization', then leaving the quotes out is better.

like image 60
Jonathan Leffler Avatar answered Nov 12 '22 04:11

Jonathan Leffler