且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-21 15:55:26

You can use the sed expression:

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

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\)'

All together:

find . -iregex '.*\.\(h\|cpp\|hpp\)' -exec sed -i.bak 's/throw some::lengthy::exception();/throw CreateException(some::lengthy::exception());/g' {} \;

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

Variable pattern

If your pattern varies, you can use:

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

This does the replacement in the lines starting with throw. It catches everything after throw up to ; and prints it back surrounded by CreateException();`.

Test

$ 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();