19

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.

tester
  • 22,441
  • 25
  • 88
  • 128

1 Answers1

25

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.

johnsyweb
  • 136,902
  • 23
  • 188
  • 247
  • not sure why you updated it to pipe into head. what you had before ( `ack -o '.{0,20}string.{0,20}'` ) did the trick. Thanks – tester Nov 12 '11 at 00:53
  • 3
    Thats awesome Thanks! Now if only there was a way to preserve the highlighting – nolanpro Jan 03 '13 at 17:59