tags:

views:

120

answers:

2

I run the following code

sed 's/\([^ ]+\) your \([^ ]+\)/ \2\1er/' < fail

The file fail is

fail your test

The above command gives me

fail your test

although it should give "testfailer".

The second and first globs \2\1 should be at the start of the word "er". This suggests me that the problem may be in the regexes in the search part. However, they seem to be correct for me.

Do you see any mistake in the code?

+5  A: 

Common or garden variety sed regex doesn't understand +. Yeah, I know, how stupid is that. So this is an equivalent, working version of your command line:

sed 's/\([^ ][^ ]*\) your \([^ ][^ ]*\)/ \2\1er/' < fail

Also works to request extended regex, in which case you ditch the backslashes on the parens:

sed -r 's/([^ ]+) your ([^ ]+)/ \2\1er/' < fail
chaos
Would the {1,} quantifier work?
Tomalak
Works in basic regex if you backslash the braces, in extended regex if you don't.
chaos
Backslashing the + in basic is less effort, though. :)
chaos
@chaos: Thanks. :)
Tomalak
+4  A: 

Your code does work when you escape the plus signs:

sed 's/\([^ ]\+\) your \([^ ]\+\)/\2\1er/' < fail
Stephan202
Ah, I see now. + and () are considered extended regex features, so you enable them in 'basic' mode by backslashing them. Good to know.
chaos
I did not get the code to work in OSX Leopard.
Masi
@Stephan: Your code works in Ubuntu.
Masi
It seems that Leopard does not even have sed which has the quantifiers +, * and ?. I did not find Gnu Sed in MacPorts.
Masi
The name of Gnu Sed in MacPorts is gsed.
Masi
@Masi: what's more, I only tested the code on Ubuntu 8.10 :)
Stephan202