0

How can I grep key word and the next four words. For example let's say we have this paragraph:

Meta Stack Exchange is where users like you discuss bugs, features, and 
support issues that affect the software powering all 167 Stack Exchange 
communities.

I wan to grep the key word "Exchange " and the next four words so the output is "Exchange is where users like"

I used :

grep -Eo "Exchange" 

What I must add to this command to control the number of greps (words, numbers, charters ,...) after a key word

  • try something like: grep -Eo 'Exchange ([aA-zA]+) ([aA-zA]+) ([aA-zA]+) ([aA-zA]+)' – zee May 13 '17 at 23:59
1

Using sequences of space and non-space characters maybe?

$ grep -Eo 'Exchange([[:space:]]+[^[:space:]]+){4}' << EOF
Meta Stack Exchange is where users like you discuss bugs, features, and 
support issues that affect the software powering all 167 Stack Exchange 
communities.
EOF
Exchange is where users like

or (perl-style, if your grep supports it)

$ grep -Eo 'Exchange(\s+\S+){4}' << EOF
Meta Stack Exchange is where users like you discuss bugs, features, and 
support issues that affect the software powering all 167 Stack Exchange 
communities.
EOF
Exchange is where users like

Note that grep does not match across lines - for multi-line matches, you can use pcregrep instead.

  • Qsteeldriver. Thank you very much! I spent three days Googling for it and I was unable to find it ;-). Kindly one more question: how this command can be revised to grep the previous four words of a match? – user88036 May 14 '17 at 0:00
  • 1
    @goro that should be obvious, no? – steeldriver May 14 '17 at 0:08
  • 100% Obvious ;-)) Thank you very much! – user88036 May 14 '17 at 0:10

Your Answer

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