RegEx find and replace with sed, matching group and replacing on condition

itunesregexscriptsed

Is this possible with sed?

I'm actually in iTunes using "Track Name Edit with sed" from Doug's Scripts, and I have a collection of tracks that are titled in one of two ways:

Identical string - Identical string

or

Some string - some different string

In the first case, I want to remove one of the identical strings and the middle - so I am left with just a single iteration of the "Identical string." If the strings are different (second case), I want to leave it alone.

I tried s/^(.*) - $1/$1/, but it appears I can't match to a group I just defined. s/^(.*) - (.*)/$1/ will work for the first case, obviously, but will incorrectly process for the second case. Is there another way around this using the tools I've mentioned?

Best Answer

You can reference groups you just defined, but sed uses \n, not $n, for that. In addition, grouping with ( ) only works in "extended" mode (enable with the -r option):

sed -r 's/^(.+) - \1/\1/'

In "basic" mode, you'd use:

sed 's/^\(.*\) - \1/\1/'
Related Question