Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Is there any way to give grep some context? It's great knowing what file a word came from, but I've never figured out how to get grep to spit out the leading and following lines too.


from `man grep`:

     -A NUM, --after-context=NUM
            Print  NUM  lines  of  trailing context after matching lines.  Places a
            line containing a group separator (--)  between  contiguous  groups  of
            matches.  With the -o or --only-matching option, this has no effect and
            a warning is given.

     -B NUM, --before-context=NUM
            Print NUM lines of leading context before  matching  lines.   Places  a
            line  containing  a  group  separator (--) between contiguous groups of
            matches.  With the -o or --only-matching option, this has no effect and
            a warning is given.

     -C NUM, -NUM, --context=NUM
            Print  NUM  lines  of output context.  Places a line containing a group
            separator (--) between contiguous groups of matches.  With  the  -o  or
            --only-matching option, this has no effect and a warning is given.


Not that obvious (even from this description): you can simply do a grep -3 to get three lines of context, etc.


I use a function that looks like this:

  find $1 -name $2 | xargs egrep -nC3 $3 | less
So, say:

  find ./ -name "*.rb" | xargs egrep -nC3 'gsub' | less
You'll get the matching line, three lines before and three lines after, as well as file name and line numbers.


awk and perl will let you do magic, my friend. Advanced "grep" features are only in GNU grep.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: