I wish to list all header files in a C file using a Bash script
#include <stdio.h> // in output it should print stdio.h
I wish to list all header files in a C file using a Bash script
#include <stdio.h> // in output it should print stdio.h
Personally, I'd probably use sed
:
sed -n -e 's/^#include[[:space:]]*[<"]\([^>"]*\)[>"].*/\1/p' "$@"
and I might put a [[:space:]]*
unit before the #
and after the #
to allow for optional spacing. That covers the vast majority of cases. You can have
#define STDIO_H <stdio.h>
#include STDIO_H
and the script won't spot that. You could also have a backslash-newline in the material and the script won't spot that, either. And it doesn't handle comments embedded in the line:
#include <stdio.h> // This one is detected OK
/*#*/#/*$*/include\
/\
* This one is not!
*\
/\
<stdlib.h>
OTOH, I don't care. Anyone who wrote code like that second #include
except as a torture test for the compiler deserves to be…treated with disdain and not allowed to check their code into the version control system. (Note: I forebore from using trigraphs in that code.)
You don't need any bash script. A grep one-liner will do this job.
grep -oP "#include\s*<\K[^>]*" file
\K
discards the previously matched characters from printing at the final. So that the output won't contain #include<
part.