Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
languagebash
perl -n -e 'print if $_=~/<some pattern>/;'

# for example:
echo -e "12\n23\n4\n5" | perl -n -e 'print if $_ =~/\d\d/'


# or, for lines not matching
echo -e "12\n23\n4\n5" | perl -n -e 'print if $_ !~/\d\d/'

Gory details:

  • -n tells perl to feed the input to the script one line at a time
  • -e introduces the perl script (always encode it in single quotes to protect it from shell evaluation)
  • $_ is a built-in variable holding the current line
  • =~ is the perl pattern matching operator (=~ says pattern must match; ! ~ says pattern not matching)
  • the forward slashes ("/  /") enclose the regex pattern

...

The sed command can be used to edit text using pattern substitution. While it is very powerful, the regex syntax for some of its more advanced features is quite different from "standard" grep or perlregexesregular expressions. As a result, I tend to use it only for very simple substitutions, usually as a component of a multi-pipe expression.

...