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

1

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.

Rightist answered 12/11, 2011 at 0:34 Comment(2)
The real solution is to be able to ignore minified Javascript, and that's coming in ack 2.0.Poster
Possible duplicate of Grep characters before and after match?Imperception
I
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.

Intolerant answered 12/11, 2011 at 0:36 Comment(2)
not sure why you updated it to pipe into head. what you had before ( ack -o '.{0,20}string.{0,20}' ) did the trick. ThanksRightist
Thats awesome Thanks! Now if only there was a way to preserve the highlightingQianaqibla

© 2022 - 2024 — McMap. All rights reserved.