Extended regular expression new line

I seem to match two things using extended regular expressions:

  1. Newline. I have tried [ \n], [ \\n], both don't work
  2. Negative lookahead for string "timeout". I have tried (?!timeout)

Can anyone please point out the correct way?

1

1 Answer

Newline

If you're using bash, you can write $'\n'. This gets expanded by the shell, not the program, so it's more reliable than other options.

If you're using dash (e.g., inside a shell script), you can always use a literal quoted newline:

'
'

Not elegant, but it works.

Lookahead

You'll have to use Perl Compatible Regular Expressions (-P), since extended regular expressions do not support lookaheads.

Oftentimes, it's sufficient to mimic negative lookaheads.

Using grep's -v switch usually accomplishes this:

grep -E 'PATTERN' | grep -vE 'PATTERNtimeout'

is equivalent to

grep -P 'PATTERN(?!timeout)'

To mimic (?!timeout) inside another expression, you can use this subexpression:

(($|[^t])|t($|[^i])|ti($|[^m])|tim($|[^e])|time($|[^o])|timeo($|[^u])|timeou($|[^t]))
  • ($|[^t]) string ends here or first character is not t.
  • t($|[^i]) string ends after t or second character is not i.
  • ti($|[^m]) string ends after ti or third character is not tim.
  • ...

If any of the above matches, the string is not timeout.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like