Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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


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?

share|improve this question
sed only ever replaces on condition i.e. on condition that it matches! there isn't really a question of how to make sed replace on condition! certainly not in the sense of on condition that it matches, which is what you mean. if you just tried simpler examples you'd soon see that your problem is that it is matching when you think it shouldn't or isn't matching when you think it should. – barlop Sep 17 '11 at 20:16
do you have a version of sed that uses $1? which version is that? you say "s/^(.*) - (.*)/$1/ will work for the first case, obviously," – barlop Sep 17 '11 at 20:18
up vote 4 down vote accepted

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/'
share|improve this answer
Second option was exactly what I needed! I'm not calling sed myself from within this iTunes applescript, so it appears as though it was running in Basic mode. Thanks! – NReilingh Sep 17 '11 at 20:59
+1 for the -r option – Serge Wautier Aug 16 '12 at 14:51

this works , gnuwin32 sed. GNU sed 4.2.1

C:\tes>echo ident - ident | sed -r "s/^(.*) - \1 /z/"

C:\tes>echo ident - idrnt | sed -r "s/^(.*) - \1 /z/"
ident - idrnt

C:\tes>echo ident - ident | sed -r "s/^(.*) - \1 /\1/"

C:\tes>echo ident - idevt | sed -r "s/^(.*) - \1 /\1/"
ident - idevt

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .