Search code examples
grepfilteringack

grep/ack -o with characters of context (not lines)


I'm trying to find a way to

grep -o "somepattern"

which gives me something like

html/file.js
2:somepattern
5:somepattern

but what would be really nice is to have a few characters (maybe 20) before and/or after that match.

I know there is a way to show lines before and after (context), but is there any way to show context by characters? e.g.

html/file.js
2:function helloWorld(somepattern) {
5:    var foo = somepattern;

The reason I ask is that if I grep recursively and hit a minified file with a match, it prints the entire file, which is super annoying.


Solution

  • Using ack:

    % ack -o '.{0,10}string.{0,10}' | head
    cli/cmdlineparser.cpp:22:#include <string>
    cli/cmdlineparser.cpp:23:include <cstring>
    cli/cmdlineparser.cpp:37:onst std::string& FileList
    ctor<std::string>& PathNam
    cli/cmdlineparser.cpp:57:     std::string FileName;
    cli/cmdlineparser.cpp:66:onst std::string& FileList
    list<std::string>& PathNam
    cli/cmdlineparser.cpp:72:     std::string PathName;
    cli/cmdlineparser.cpp:92:onst std::string &message)
    cli/cmdlineparser.cpp:133:onst std::string errmsg = 
    

    Using (Gnu) grep:

    % grep -no '.\{0,10\}string.\{0,10\}' **/*.[ch]* | head
    cli/cmdlineparser.cpp:22:#include <string>
    cli/cmdlineparser.cpp:23:include <cstring>
    cli/cmdlineparser.cpp:37:onst std::string& FileList
    ctor<std::string>& PathNam
    cli/cmdlineparser.cpp:57:     std::string FileName;
    cli/cmdlineparser.cpp:66:onst std::string& FileList
    list<std::string>& PathNam
    cli/cmdlineparser.cpp:72:     std::string PathName;
    cli/cmdlineparser.cpp:92:onst std::string &message)
    cli/cmdlineparser.cpp:133:onst std::string errmsg = 
    

    ...shows up to 10 characters before and 10 characters after 'string'... (assuming they're there).

    I'm using | head here merely to limit the output to 10 lines for clarity.