Find With Multiple Greps

- 1 answer

I need to find lines of code after malloc that does not contain the word null, so that I can understand if the malloc was properly checked or not.

For example the following lines should be printed:

obj = (boolean *) malloc(DAYS_IN_WEEK * sizeof(boolean));
    for(int i = 0; i < DAYS_IN_WEEK; i++){

This command partially works since it prints out the lines containing malloc

find . -type f -name '*.c' \( -exec grep -HnA2 'malloc' {}  \;

should I add another grep? Not sure how to do it.



There must be something easier but this seems close:

find . -name "*.c" -exec grep -nHA1 malloc {} \; | 
   awk '/^--/ {next} /malloc/{f=1; p=$0; next} f==1 && !/NULL/{f=0; print p; print $0}'


  • /^---/ {next} ignores all lines starting with dashes that grep generates
  • /malloc/{f=1;p=$0;next} sets a flag f if the line contains malloc then remembers the line in p and moves to the next
  • f=1... checks if the flag is set (i.e. the previous line contained malloc) and the current line doesn't contain NULL, and if so, prints the previous and current lines