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