Search code examples
perlawksedgrepag

File searching and proximity search


I've been looking at grep a file, but show several surrounding lines?

I'm using a bash terminal, looking for a file which

  • Has both path and redirect on any one line

  • Has flash on a nearby line, within five lines from the first

In this possible with grep, ag, Perl, sed or any tool you guys know of?


Solution

  • The easier filter is the one with "flash". It is also good to do it first, so that the more expensive pattern matching is done in the subset of matched files.

    For this, just say:

    grep -RH -C 5 "text" *
    

    This will recursively (-R) look for the pattern "text" and print the name of the file (-H) when this happens. Also, it will print the surrounding 5 lines (-C 5). Just change 5 with a variable if you want so.

    Then it is time to use awk to check two patterns with:

    awk '/pattern1/ && /pattern2/ {print FILENAME}' file
    

    This is useful as awk is quite good on multiple patterns matching.

    Since we do not have the filename but a stream on the form filename:flash, etc, we can have a basic Bash loop to handle the result from grep:

    while IFS=":" read -r filename data;
    do
        awk -v f="$filename" '/path/ && /redirect/ {print f}' <<< "$data"
    done < <(grep -RH -C5 "text" *)