void
void

Reputation: 358

sed/awk: Insert some text in a file after the last pattern found

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

Answers (4)

user13500
user13500

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

kev
kev

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 twice
  • first time if FNR==NR

Upvotes: 3

sat
sat

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

user1907906
user1907906

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

Related Questions