在特定目录的文件中查找和替换字符串

find and replace strings in files in a particular directory

我有一个模式需要在多个目录的 .hpp.h.cpp 文件中替换。

我已阅读 Find and replace a particular term in multiple files question for guidance. I am also using 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/\bthrow some::lengthy::exception();/throw CreateException(some::lengthy::exception());/g' *.cpp

添加内联编辑 -i 参数以保存更改。

您可以使用以下内容:

sed 's/\b(throw some::lengthy::exception());/throw CreateException();/g'

您可以使用 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();/' file

这会替换以 throw 开头的行。它捕获 throw; 之后的所有内容,并将其打印回 CreateException();`.

测试

$ cat a.hpp 
throw some::lengthy::exception();
throw you();
asdfasdf throw you();
$ sed -r '/^throw/s/throw (.*);$/throw CreateException();/' a.hpp 
throw CreateException(some::lengthy::exception());
throw CreateException(you());
asdfasdf throw you();