sed equivalent of perl -pe

Viewed 190

I'm looking for an equivalent of perl -pe. Ideally, it would be replace with sed if it's possible. Any help is highly appreciated.

The code is:

perl -pe 's/^\[([^\]]+)\].*$/$1/g'
1 Answers
$ echo '[foo] 123' | perl -pe 's/^\[([^\]]+)\].*$/$1/g'
foo

$ echo '[foo] 123' | sed -E 's/^\[([^]]+)\].*$/\1/'
foo
  • sed by default accepts code from command line, so -e isn't needed (though it can be used)
  • printing the pattern space is default, so -p isn't needed and sed -n is similar to perl -n
  • -E is used here to be as close as possible to Perl regex. sed supports BRE and ERE (not as feature rich as Perl) and even that differs from implementation to implementation.
    • with BRE, the command for this example would be: sed 's/^\[\([^]]*\)\].*$/\1/'
  • \ isn't special inside character class unless it is an escape sequence like \t, \x27 etc
  • backreferences use \N format (and limited to maximum 9)
  • Also note that g flag isn't needed in either case, as you are using line anchors
Related