Reputation: 522
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
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
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
Reputation: 5351
I don't have the time to work out a complete script, but here's an idea:
grep
to find only the files containing #include "my.hpp"
and run the following stages only on these filessed 's/#include "my.hpp"'//
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