3

How to extract headers from a c file that contains them like this?

#include <tema4header9.h>
#include    <tema4header3.h>
#include   <stdio.h>
#include        <longnametest/newheader.h>
#include <net/header.h>
#include  "last-test-Zhy3/DrRuheader.h"
#include <last-test-8fF7/a5xyheader.h>

I tried to use:

sed -n -e 's/#include[ \t]*[<"]\([^ \/<"]*\/[^ \/]*\)\.h[">]/\1\.h/p'

but it only works for those in subdirectories. also if i type:

sed -n -e 's/#include[ \t]*[<"]\(([^ \/<"]*\/)+[^ \/]*\)\.h[">]/\1\.h/p'

or

sed -n -e 's/#include[ \t]*[<"]\(([^ \/<"]*\/)*[^ \/]*\)\.h[">]/\1\.h/p'

the command does not work anymore. The output file should look like this:

tema4header9.h
tema4header3.
stdio.h
longnametest/newheader.h
net/header.h
last-test-Zhy3/DrRuheader.h
last-test-8fF7/a5xyheader.h
Cœur
  • 34,719
  • 24
  • 185
  • 251
adikinzor
  • 55
  • 1
  • 5

4 Answers4

2

grep solution: This is using perl regex and printing anything between "<" or '"' on the lines which start with #include.

grep -oP '^#include.*(<|")\K.*(?=>|")' headers
tema4header9.h
tema4header3.h
stdio.h
longnametest/newheader.h
net/header.h
last-test-Zhy3/DrRuheader.h
last-test-8fF7/a5xyheader.h

If you are ok with awk:

awk '/#include/{gsub(/<|>|"/,"",$2);print $2}' headers
tema4header9.h
tema4header3.h
stdio.h
longnametest/newheader.h
net/header.h
last-test-Zhy3/DrRuheader.h
last-test-8fF7/a5xyheader.h
P....
  • 14,772
  • 2
  • 24
  • 42
1

This should work:

sed -nr 's/#include\s+[<"]([^>"]+)[>"].*/\1/p'
klarsen
  • 11
  • 3
0

Try:

awk '{match($0,/[<"].*[>"]/);print substr($0,RSTART+1,RLENGTH-2)}' Input_file
RavinderSingh13
  • 117,272
  • 11
  • 49
  • 86
0

Like above:

sed -n 's/\s*#\s*include\s*[<"]\(.\+.h\)[>"]/\1/p' input_file

but it is more precise, for example, the input_file content is:

 # include <stdio.h>
       #        include<stdlib.h>
    #    include    <time.h>
 #define LEN 8
 #define OPT 2
 #include <pthread.h>
 # include "mysql.h"
 #include "paths.h"

it can still print right:

stdio.h
stdlib.h
time.h
pthread.h
mysql.h
paths.h
Li-Guangda
  • 191
  • 1
  • 2
  • 12