Appending a line in a file after a particular line

Hello,

I have got a C file in which I would like to add an include statement of my own.
There are already a few include statements and mine should come right after the last existing one (to be neat).

With grep I can get the lines containing the word 'include' and I guess I should feed the last line of the result to a sed command to append a line but I don't know exactly how to do this part. Any suggestions ?

Thanks a lot in advance
Max

The normal approach to editing C files is to use a text editor such as vi or emacs.

Are you trying to update many C source files?

Yes, this is part of the process of updating many C files which cannot be reasonably made by hand.

by using the following:

sed '/#include/ a\
#include "myHeader.h"' input > ouput

it adds my header after each line already calling a header. Is there a means to make this happen only after the last existing include ?

Max

If awk is allowed:

awk ' 
$1=="#include"{f=1}
$1!="#include" && f{f=0;print str}1
' str="#include My.h" file.c

Regards

sed '/^#include/{
n;/^#include/!{i\
#include "myHeader.h"
}
}' input > output

Brilliant, that's working like magic !

However, I don't understand at all the syntax of your code so I'll have a look at awk in further details.

Thanks
Max

The solution with sed worked fine as well.

Thanks !!
Max

The explanation is fairly simple. When sed comes across a line that starts with "#include" it fetches the next line. If the next line just fetched does not begin with "#include" sed inserts the #include "myHeader.h" line at that spot.