I had to move some existing code into a namespace. As it was too much code for doing this manually, I developed the following bits of shell script:
#!/bin/bash
#
#############################################################
# "THE BEER-WARE LICENSE" (Revision 42):
# <robert -at- xenim -dot- de> wrote this file. As long as you
# retain this notice you can do whatever you want
# with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return.
#############################################################
NAMESPACE="mynamespace"
SRCDIR=/path/to/sources
find $SRCDIR -name '*.cpp' | while read f; do
LNUM=`awk '/#include/{a=NR}; END{print a}' "$f"`;
if [ ! -z "$LNUM" ]; then LNUM=1; fi;
sed -i -e "$LNUM a \\\nnamespace $NAMESPACE {" -e '$,$ a } /* end namespace $NAMESPACE */' "$f";
done
find $SRCDIR -name '*.h' | while read f; do
LNUM=`awk '/#include/{a=NR}; END{print a}' "$f"`;
if [ -z "$LNUM" ]; then
LNUM=`awk '/#define/{a=NR}; END{print a}' "$f"`;
fi;
sed -i -e "$LNUM a \\\nnamespace $NAMESPACE {" "$f";
LNUM=`awk '/#endif/{a=NR}; END{print a}' "$f"`;
sed -i -e "$LNUM i } /* end namespace $NAMESPACE */\n" "$f";
done
The first find loops over all source-files (assumed suffix is .cpp here) and inserts a namespace-declaration after the last occuring #include. If you keep all #inludes at the top of your file, this should work fine. The corresponding closing bracket is simply added at the end of the file.
The second loop edits the header-files. The namespace-declaration is also added after the last #include if there is any. Otherwise the declaration is inserted right after the include-guard. The closing bracket is added here before the include-guard ends.
And finally the usual warning: Backup your files before using this!