Globbing and grouping issue in a regex in sed

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?

Upvotes: 1

Views: 2074

Answers (2)

Stephan202
Stephan202

Reputation: 61559

Your code does work when you escape the plus signs:

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

Upvotes: 4

chaos
chaos

Reputation: 124325

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

Upvotes: 5

Related Questions