Advanced sed regex

Some sed regex stuff I finally understood:

  • always use single quotes or you will go insane with escaping or strange errors
  • there is no \d and no +(at least on mac, on gnu its \+ (thx tobi!)), but you can use \{1,\} or repeat the pattern
    echo a1235b | sed 's/[0-9]\{1,\}//' --> ab
    echo a1235b | sed 's/[0-9][0-9]*//' --> ab
  • () and {} are escaped by default
    echo a{()}b | sed 's/{()}//' --> ab
  • escape ( and { to use them normal
    echo acccb | sed 's/\(c\{3\}\)/\1-\1/' --> accc-cccb
  • the matched string is &, matches from braces are \x
    echo acccb | sed 's/c\(c\)\(c\)/-&-\1-\2/' --> a-ccc-c-cb
  • To only print matched lines, use -n and /p
    echo 123 | sed -n 's/5/x/p' --> nothing
    echo 123 | sed -n 's/1/x/p' --> 1x3

2 thoughts on “Advanced sed regex

  1. I guess you are using the BSD version of sed (which is used by Mac OS X). However in the GNU version you can use the plus (but you have to escape it like the brackets).

    $ echo a1235b | sed ‘s/[0-9]\+//’

    regards, Tobi

  2. Nope, just missed it, since * worked as normal i suspected + just did not work, thanks for the tip, will save me some keystrokes and make those regexes more readable!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s