Adding namespace declarations to many files?
Say I have a lot of c++ files that I want to add namespace declarations to. i.e. I want the file to look like:
//pre-processor commands and other stuff not in the namespace
namespace foo
{
//previously existing code
}
//EOF
Any way to do this without having to open each file manually? Best I've been able to come up with so far is an emacs macro to do it to each f开发者_运维知识库ile, but I still have to go through each of them.
#!/bin/bash
for f in *.h
do
line=`grep -n '^#' $f | tail -1 | cut -f1 -d:`
head -$line $f > tempfile
echo 'namespace foo {' >> tempfile
let line++
tail --lines=+$line $f >> tempfile
echo '} // end namespace foo' >> tempfile
mv tempfile $f
done
This will go through each header file in the current directory, and:
- find the last preprocessor line (aka line that starts with '#')
- dump the first part of the file to a temp file
- add the line to open the namespace
- add the rest of the existing file
- add the line to close the namespace
- replace the file with the temp file
Note that if you want to hit cpp files too, that first line will need to be for f in *.h *.cpp
. But if your cpp files have static functions or an anonymous namespace, then this won't work.
Note that this assumes that your header files are not guarded with the classic include guard. It assumes all the preprocessor commands are in the top part of the file. If that is not the case, you'll have to make some adjustments. Try it out on some of your files, tweak as needed, and try it out on a few more.
精彩评论