How to find patterns across multiple lines using grep?

后端 未结 26 1726
你的背包
你的背包 2020-11-22 04:14

I want to find files that have \"abc\" AND \"efg\" in that order, and those two strings are on different lines in that file. Eg: a file with content:

blah bl         


        
26条回答
  •  再見小時候
    2020-11-22 04:27

    The filepattern *.sh is important to prevent directories to be inspected. Of course some test could prevent that too.

    for f in *.sh
    do
      a=$( grep -n -m1 abc $f )
      test -n "${a}" && z=$( grep -n efg $f | tail -n 1) || continue 
      (( ((${z/:*/}-${a/:*/})) > 0 )) && echo $f
    done
    

    The

    grep -n -m1 abc $f 
    

    searches maximum 1 matching and returns (-n) the linenumber. If a match was found (test -n ...) find the last match of efg (find all and take the last with tail -n 1).

    z=$( grep -n efg $f | tail -n 1)
    

    else continue.

    Since the result is something like 18:foofile.sh String alf="abc"; we need to cut away from ":" till end of line.

    ((${z/:*/}-${a/:*/}))
    

    Should return a positive result if the last match of the 2nd expression is past the first match of the first.

    Then we report the filename echo $f.

提交回复
热议问题