unix - search a word in next lines after a first word has been found -
let's take example file textfile.txt :
foo bar foo bar foo**word1**bar foo bar**word2**foo foo foo bar foo**word1**bar foo foo bar**word2**foo foo foo bar foo**word1**bar foo bar**word2**foo foo bar foo**word1**bar foo bar foo bar bar**word2**foo foo what trying : search first word in file, here word **word1**, , if word has been found, search in same line , next 2 second word, here it's **word2**
i tried use grep search **word1**, -n option line number. line number, extract sed matching line , next two, , other grep search **word2**. should match each time **word1** , **word2**.
but doesn't feel it's best way achieve this.
in example, there should 3 positive matches : last 1 doesn't work because **word2** 4 lines ahead **word1**, , want maximum of 2 lines ahead.
concerning awk's output, output line numbers 2 words matched, , respective lines have been found.
i have shell script returning output. : each matching couple words, print "my_script_result" + "awk_result" > file
this awk one-liner may help:
awk '/word1/{ok=1}ok && /word2/{print nr,$0}' file in above line, /word1/ first word, /word2/ second word. output matched line numbers , matched lines.
it works in way:
the script reads lines beginning of file, once word1 found, set variable ok =1 (true). 2nd part check ok , word2 matched, if satisfied, print output. thus, if word2 matched before found word1, ok false, line skipped.
edit according op's update:
awk /word1/{ok=1;s=nr}ok && nr<=s+2 && /word2/{print nr,$0}' file 7 bar**word2**foo 20 bar**word2**foo
Comments
Post a Comment