So I've got giant code base that needs to have a namespace added to it. Instead of doing this manually, I thought of using grep, xargs & sed to add the namespace to all source files...
But my skills are not up to par. Ideally
namespace foo
{
Would be added after all the includes, and '}' added after the #endif in the .h files.
For the .cpp files, adding 'using namespace foo' after all the includes would be sufficient.
I've been messing around with sed, but haven't gotten very far.
Any help would be appreciated. Thanks!
This is not an easy task. Things that make it problematic include
language "C" { C-stuff }
namespace Foo {
and the closing '}' can be tough.
language C
.template
declaration, if any, and of course doxygen comments and the like.Good luck! A script will take a bit more than a half an hour to write. It will take far less time than rewriting all your code. I suggest that you use something a tad more powerful than sed. Perl, python, and ruby are three good choices.
This got me half way:
#!/bin/sh
NAMESPACE=my_namespace
for x in $(find . -name "*.h"); do
sed -i "$(grep -n "^#" $x | tail -2 | head -1 | sed 's/:.*//')a\\\nnamespace $NAMESPACE {\n" $x
sed -i "$(($(grep -n "^#" $x | tail -1 | sed 's/:.*//')-1))a} // namespace $NAMESPACE\n" $x
done
for x in $(find . -name "*.cpp"); do
sed -i "$(grep -n "#include" $x | tail -1 | sed 's/:.*//')a\\\nnamespace $NAMESPACE {\n" $x
echo >> $x
echo "} // namespace $NAMESPACE" >> $x
done
It mostly locates the one but last preprocessor directive in the h file and adds the namespace there. it colses the namespace right before the last preprocessor directive (I assume that I have an #endif
at the end of my h files). If that's not the case, The script can be adapted accordingly.
In the cpp case, I look for the last include to open the namespace and close it at the end of the file.
This is far from perfect, but facing with 100+ files it made the job a lot easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With