Tuesday, May 3, 2011

Unable to understand a line 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?

From stackoverflow
  • 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
    
    Tomalak : Would the {1,} quantifier work?
    chaos : 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. :)
    Tomalak : @chaos: Thanks. :)
  • Your code does work when you escape the plus signs:

    sed 's/\([^ ]\+\) your \([^ ]\+\)/\2\1er/' < fail
    
    chaos : Ah, I see now. + and () are considered extended regex features, so you enable them in 'basic' mode by backslashing them. Good to know.
    Masi : 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.
    Stephan202 : @Masi: what's more, I only tested the code on Ubuntu 8.10 :)

0 comments:

Post a Comment