-1

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
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Tejesh Raut
  • 373
  • 5
  • 14

2 Answers2

3

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.)

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • Disappointed that you decided to skip the example with trigraphs! ;) – William Pursell Aug 16 '15 at 05:16
  • @WilliamPursell: If you want something complex, consider `#include <./*same*/header.h>`; how much of that is comment? Similarly `#include <.//header.h>`. And, for grins: `#include <./*same/header.h>`, not to mention `#include ` (there you are — some trigraphs!). – Jonathan Leffler Aug 16 '15 at 05:20
1

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.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 2
    People are sensible to write a Bash script to encapsulate this task if it is going to be done very often (say more than twice). Especially if the regex is moderately complex. Why are you matching up to a single quote instead of a `>`? – Jonathan Leffler Aug 15 '15 at 15:48