Grep max words before and after match

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

Is it possibile to make grep show a maximum number of words before and after the match? For example, given the row

aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll mmm nnn ooo ppp qqq rrr sss

I d like grep not to return whole line, but only, say, 3 words before and after the match. for example, searching for iii , the result would be

fff ggg hhh iii jjj kkk lll

I ve tried this but no result is returned:

grep -o  w{0, 20}MY_SEARCHw{0, 20}  *

Answers

string= aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll mmm nnn ooo ppp qqq rrr sss 

echo $string | grep -oP  (([a-zA-Z]+) ){0,3}iii( ([a-zA-Z]+)){0,3} 

If I ve understood your question right, this should do it when the maximum number of words on either side are 3.

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/8982712/grep-max-words-before-and-after-match

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils