我有一个模式需要在多个目录的.hpp
,.h
,.cpp
文件中替换。
我已阅读Find and replace a particular term in multiple files问题以获取指导。我也正在使用this教程,但无法实现我打算做的事情。这是我的模式。
throw some::lengthy::exception();
我想用这个代替它
throw CreateException(some::lengthy::exception());
我该如何实现?
更新:
此外,如果
some::lengthy::exception()
部分是变体,使得每个搜索结果都发生变化,该怎么办?就像是
throw some::changing::text::exception();
将转换为
throw CreateException(some::changing::text::exception());
最佳答案
您可以使用sed
表达式:
sed 's/throw some::lengthy::exception();/throw CreateException(some::lengthy::exception());/g'
并将其添加到
find
命令中以检查.h
,.cpp
和.hpp
文件(想法来自List files with certain extensions with ls and grep):find . -iregex '.*\.\(h\|cpp\|hpp\)'
全部一起:
find . -iregex '.*\.\(h\|cpp\|hpp\)' -exec sed -i.bak 's/throw some::lengthy::exception();/throw CreateException(some::lengthy::exception());/g' {} \;
请注意
sed -i.bak
的用法,以便进行适当的编辑,但要创建file.bak
备份文件。可变模式
如果您的模式有所不同,则可以使用:
sed -r '/^throw/s/throw (.*);$/throw CreateException(\1);/' file
这会在以
throw
开头的行中进行替换。它捕获从throw
到;
的所有内容,并将其打印回由CreateException();`包围的内容。测试
$ cat a.hpp
throw some::lengthy::exception();
throw you();
asdfasdf throw you();
$ sed -r '/^throw/s/throw (.*);$/throw CreateException(\1);/' a.hpp
throw CreateException(some::lengthy::exception());
throw CreateException(you());
asdfasdf throw you();
关于regex - 查找和替换特定目录中文件中的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30216419/