Versions Compared

Key

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

...

If grep pattern matching isn't behaving the way I expect, I turn to perl. Here's how to invoke regex pattern matching from a command line using perl:

...

languagebash

perl

...

-n

...

-e

...

'print

...

if

...

$_=~/

...

<pattern>/

...

'

For example:

Code Block
languagebash
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/'

...

If sed pattern substitution is not working as I expect (which happens frequently!), I again turn to perl. Here's how to invoke regex pattern substitution from a command line:

...

...

perl

...

-p

...

-e

...

'~s/<search

...

pattern>/<replacement>/

...

'

For example:

Code Block
languagebash
cat joblist.txt | perl -ne 'print if $_ =~/SA18\d\d\d$/' | \
  perl -pe '~s/JA/job /' | perl -pe '~s/SA/run /'

# Or, using parentheses to capture part of the search pattern:
cat joblist.txt | perl -ne 'print if $_ =~/SA18\d\d\d$/' | \
  perl -pe '~s/JA(\d+)\tSA(\d+)/job $1 - run $2/'

Gory details:

  • -p tells perl to print its substitution results
  • -e introduces the perl script (always encode it in single quotes to protect it from shell evaluation)
  • ~s is the perl pattern substitution operator
  • forward slashes ("/  /  /") enclose the regex search pattern and the replacement text

...