查找和替换特定目录中文件中的字符串 [英] find and replace strings in files in a particular directory

查看:37
本文介绍了查找和替换特定目录中文件中的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a pattern that I need to replace in my .hpp, .h, .cpp files in multiple directories.

我已阅读 查找和替换多个特定术语文件 问题寻求指导.我也在使用 this 教程,但我无法实现我的目标打算做.所以这是我的模式.

I have read Find and replace a particular term in multiple files question for guidance. I am also using this tutorial but I am not able achieve what I intend to do. So here is my pattern.

throw some::lengthy::exception();

我想用这个替换它

throw CreateException(some::lengthy::exception());

我怎样才能做到这一点?

How can I achieve this?

更新:

此外,如果 some::lengthy::exception() 部分是变体的,它会随着每个搜索结果而变化,该怎么办?像

Moreover, what if the some::lengthy::exception() part is variant such that it changes for every search result ? Something like

抛出一些::changeing::text::exception();

将转换为

throw CreateException(some::changeing::text::exception());

推荐答案

可以使用 sed 表达式:

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

并将其添加到 find 命令中以检查 .h.cpp.hpp 文件(想法来自 使用 ls 和 grep 列出具有特定扩展名的文件):

And add it into a find command to check .h, .cpp and .hpp files (idea coming from 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 备份文件.

Note the usage of sed -i.bak in order to to edits in place but create a file.bak backup file.

如果您的模式不同,您可以使用:

If your pattern varies, you can use:

sed -r '/^throw/s/throw (.*);$/throw CreateException(1);/' file

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

This does the replacement in the lines starting with throw. It catches everything after throw up to ; and prints it back surrounded by 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();

这篇关于查找和替换特定目录中文件中的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆