Regex 查找并替换特定目录中文件中的字符串

Regex 查找并替换特定目录中文件中的字符串,regex,sed,find,pattern-matching,Regex,Sed,Find,Pattern Matching,我需要在多个目录中的.hpp、.h、.cpp文件中替换一个模式 我已经阅读了这个问题以寻求指导。我也在使用教程,但我无法达到我想要做的。这就是我的模式 throw some::lengthy::exception(); 我想用这个来代替它 throw CreateException(some::lengthy::exception()); 我怎样才能做到这一点 更新: 此外,如果some::longle::exception部分是一个变量,因此它在每个搜索结果中都会发生变化,该怎么办? 差不

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

我已经阅读了这个问题以寻求指导。我也在使用教程,但我无法达到我想要做的。这就是我的模式

throw some::lengthy::exception();
我想用这个来代替它

throw CreateException(some::lengthy::exception());
我怎样才能做到这一点

更新:

此外,如果some::longle::exception部分是一个变量,因此它在每个搜索结果中都会发生变化,该怎么办? 差不多

抛出一些::changing::text::异常

将转换为


抛出CreateExceptionsome::Changeing::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(\1);/g'
您可以使用sed表达式:

sed 's/throw some::lengthy::exception();/throw CreateException(some::lengthy::exception());/g'
并将其添加到find命令中,以检查.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开头的行中进行替换。它把所有的东西都抓起来,直到吐出来;并将其打印回CreateException;`

测验
但这不起作用,因为sed1需要BRE语法,而您的答案使用Perl regexps.Nope。分组。。。应为\…\,并且sed1中不存在\b。但是\1可以。@lcd047。。表示\b可以用作sed中的单词边界。。不?那他们就错了\b从来不是sed1中的单词分隔符。它代表BSD sed1中的退格字符,对于大多数版本的GNU sed1,它是未定义的。shrugSorry,实际上\b似乎在GNU sed1的最新版本中起作用。不过,使用它可能仍然不是一个好主意。好的,谢谢。但是如果some::longle::exception部分是variant呢?以及每个搜索结果的更改?类似于throw[I change everytime]的内容将转换为throw CreateException[I change everytime]@为此,我需要你用一组更好的样本输入和期望的输出更新你的问题:我的坏。是的,它不包含[或]字符。但是您如何定义抛出语句?只是一行,以投掷开始,以@我已经更新了这个例子。
sed -r '/^throw/s/throw (.*);$/throw CreateException(\1);/' file
$ 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();