1

I've this command grep -oP '.*?(?=\:)' which gets words before : character, the thing I want is to get all the words after : character How can I do it?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Nobody
  • 23
  • 4

2 Answers2

3

You can use \K, which tells the engine to pretend that the match attempt started at this position. You can have something like:

grep -oP '.*:\K(.*)'

Example:

$ echo "hello:world" | grep -oP ":\K.*"
world
Maroun
  • 94,125
  • 30
  • 188
  • 241
3

If you need to get a word after the last :, you need

grep -oP '.*:\K\w+' file

If you need to get a word after the first :, you need

grep -oP '^[^:]*:\K\w+'

If you need to get all the words after a :, you need

grep -oP ':\K\w+'

If a "word" is a sequence of non-whitespace chars, you need to replace \w with \S:

grep -oP '.*:\K\S+' file
grep -oP '^[^:]*:\K\S+'

If a "word" is a sequence of any Unicode letters, you need to replace \w with \p{L}:

grep -oP '.*:\K\p{L}+' file
grep -oP '^[^:]*:\K\p{L}+'

NOTES:

  • \K is a match reset operator that clears out the current overall match memory buffer.
  • -o - option that outputs the matched substrings, not matched lines
  • -P - enables the PCRE regex engine rather than the default POSIX one.
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563