emmerich
emmerich

Reputation: 522

How could I reorder the includes in C header files?

I have a number of .cpp and .hpp files which contain an #include "my.hpp" which I want to move it in each file to be the last of the includes like this:

current:

#include "my.hpp"
#include "foo.hpp"
#include "bar.hpp"

or

#include "whatever.hpp"
#include "my.hpp"
#include "bar.hpp"

needed:

#include "whatever.hpp"
#include "something.hpp"
#include "my.hpp"

Thanks!

Upvotes: 0

Views: 97

Answers (3)

potong
potong

Reputation: 58453

This might work for you (GNU sed):

sed -rsi '/^#include\b/!b;:a;/#include\b[^\n]*$/{$bb;N;ba};:b;s/(#include my.hpp"\n)(.*)(#include\b[^\n]*\n)/\3\2\1/' file1 file2 filen

This assumes the #includes are consecutive and are not the last entries in the file.

Upvotes: 0

tamasgal
tamasgal

Reputation: 26299

There you go with find and perl:

find . -name "*.?pp" -exec perl -0777 -pi -e 's/(#include "my.hpp"\n)((#include .*\n)*)/$2$1/g' {} \;

e: forgot to add -0777 (multiple lines enabled)

Upvotes: 2

Little Bobby Tables
Little Bobby Tables

Reputation: 5351

I don't have the time to work out a complete script, but here's an idea:

  1. Run grep to find only the files containing #include "my.hpp" and run the following stages only on these files
  2. Cut the problematic include line using something like sed 's/#include "my.hpp"'//
  3. Find the last include line using tac and sed and append to it your include line - See this question and accepted answer for details. I'm guessing something like

    tac | sed 's/^\(#include .*\)$/\1\n#include "my.hpp"/q' | tac

Details may depend on your exact files, so YMMV.

Upvotes: 0

Related Questions