Reputation: 561
Let's say I have a folder with numerous modules, and I'm doing a grep
for a function. Let's say the function I'm searching for is called test()
. Is it possible to find out which functions test()
is called in? For example, let's say below is ModuleA.erl
, and we do a grep for test()
.
FunctionA()
A = 5,
B = 3,
test()
It should return:
ModuleA.erl: FunctionA()
It is safe to assume that the function definition will always be non-indented
Upvotes: 1
Views: 584
Reputation: 174706
Just run the below grep command on the directory where the .erl
files are stored.
grep -HPoz '^\S.*(?=(\n .*)+test\(\))' *.erl
From man grep
-H, --with-filename print the file name for each match
-P, --perl-regexp PATTERN is a Perl regular expression
-z, --null-data a data line ends in 0 byte, not newline
^
asserts that we are at the start. \S
matches any non-space character..*
matches any character but not of line breaks, zero or more times. (?=(\n .*)+test\(\))
Positive lookahead assertion which asserts that the match must be followed by
\n .*
A new line character and a space followed by any number of characters,
(\n .*)+
one or more times.
test\(\)
and must have a test()
string. Match will occur only if this condition was satisfied.
Test:
Folder$ cat gi.erl
FunctionA()
A = 5,
B = 3,
FunctionB()
A = 5,
B = 3,
test()
Folder$ cat ri.erl
FunctionA()
A = 5,
B = 3,
test()
FunctionB()
A = 5,
B = 3,
Folder$ grep -HPoz '^\S.*(?=(\n .*)+test\(\))' *.erl
gi.erl:FunctionB()
ri.erl:FunctionA()
Here Folder
is the folder name where all the erl
files are stored.
Upvotes: 1
Reputation: 289585
You can use awk
for this:
$ awk -v patt="test" '$0 ~ /^\w/ {f=$0} $0 ~ patt {print f}' file
FunctionA()
This stores the lines not starting with a space. If a line matches, then it prints the last stored line.
-v patt="test"
provide the pattern$0 ~ /^\w/ {f=$0}
if the current line starts with some character (not space), store its value.$0 ~ patt {print f}
if a line contains the given pattern, print the stored header.$ cat a
FunctionA()
A = 5,
B = 3,
test()
FunctionB()
A = 5,
B = 3,
another()
$ awk -v patt="test" '$0 ~ /^\w/ {f=$0} $0 ~ patt {print f}' a
FunctionA()
Upvotes: 3