假设我有很多要向其中添加 namespace 声明的c++文件。即我希望文件看起来像:
//pre-processor commands and other stuff not in the namespace
namespace foo
{
//previously existing code
}
//EOF
有什么方法可以不必手动打开每个文件?到目前为止,我能想到的最好的是一个emacs宏来对每个文件进行处理,但是我仍然必须遍历每个文件。
最佳答案
#!/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
这将遍历当前目录中的每个头文件,以及:
请注意,如果您也想访问cpp文件,则第一行必须是
for f in *.h *.cpp
。但是,如果您的cpp文件具有静态功能或匿名 namespace ,则将无法使用。请注意,这假设您的头文件没有使用经典的include保护器进行保护。假定所有预处理器命令都在文件的顶部。如果不是这种情况,则必须进行一些调整。在您的某些文件上进行尝试,根据需要进行调整,然后再进行一些尝试。