Reputation: 358
I want to insert the text
#include < abc/malloc.h>
in a C file after all the
#include
lines, just after the last occurrence of #include
.
Upvotes: 2
Views: 1427
Reputation: 3856
Assuming you can have anything between includes.
awk '
BEGIN {
x = 0
}
{
if ($0 ~ /^#include/)
x = NR
b[NR]=$0
}
END {
for (i = 1; i <= x; ++i)
print b[i]
print "#include <abc/malloc.h>"
for (i = ++x; i <= NR; ++i)
print b[i]
}
' file.c
Upvotes: 2
Reputation: 161674
Use awk
:
awk '
FNR==NR && /^#include/ { line=NR; next }
FNR!=NR
FNR==line { print "#include <abc/malloc.h>" }
' code.c code.c
As you can see:
awk
read code.c
twiceFNR==NR
Upvotes: 3
Reputation: 14949
You can try this,
tac yourfile.c | sed '/#include/{ s/#include.*/#include<someheader>\n&/; :loop;n; t loop;}'| tac > updated_yourfile.c
Upvotes: 1
Reputation:
The input:
$ cat in.h
#include <foo.h>
#include <bar.h>
/* No more includes */
/* But more stuff */
Find the last #include
line:
$ l=$(grep -n '^#include' in.h | tail -1 | cut -d: -f1)
Append a line after this line:
$ sed "$l a#include <baz.h>" < in.h
#include <foo.h>
#include <bar.h>
#include <baz.h>
/* No more includes */
/* But more stuff */
Upvotes: 2