Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can ack/ag/grep print function name?

Is it possible to print the function or class name in which a keyword occurs when using ack or ag? This is something I have highly desired for quite some time.

I think it would be quite tricky, as different programming languages have different ways of enclosing functions/classes.

Note that my goal right is for searching through C source code, however I would prefer a generic solution which covers more languages/syntax.

like image 503
shivams Avatar asked Nov 22 '25 10:11

shivams


2 Answers

Author of ack here. No, I don't know of any greplike tool that understands anything about the text files that it's searching. It's something that people ask for all the time, but I've never even thought about implementing it.

You said "I think it would be quite tricky, as different programming languages have different ways of enclosing functions/classes." You're exactly right. Also, consider things like comments

/* void foo() */

and literal strings

printf( "void foo()" );

that would cause problems for any search tool. Neither of those instances of the string void foo() is actually a function declaration.

Check out the More Tools page on beyondgrep.com. Something like cscope might help you.

like image 167
Andy Lester Avatar answered Nov 24 '25 12:11

Andy Lester


As commented by @Inian, it would be difficult to get a robust solution using ack, ag and grep as they are not aware of the grammar of the languages.

However, for my case of looking inside C source code files, I used ack with an OR condition to include lines which are starting with the function definitions. In my case, all my functions were either returning int or nothing. Hence, the following code printed out function definition lines alongwith the lines containing the KEYWORD:

ack 'KEYWORD|^void|^int'
like image 40
shivams Avatar answered Nov 24 '25 12:11

shivams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!