Reputation: 1973
I have a pattern that I need to replace in my .hpp
, .h
, .cpp
files in multiple directories.
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();
I want to replace it with this
throw CreateException(some::lengthy::exception());
How can I achieve this?
UPDATE:
Moreover, what if the some::lengthy::exception()
part is variant such that it changes for every search result ?
Something like
throw some::changing::text::exception();
will be converted to
throw CreateException(some::changing::text::exception());
Upvotes: 1
Views: 308
Reputation: 289725
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.
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();`.
$ 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();
Upvotes: 2
Reputation: 13640
You can use the following:
sed 's/\b(throw some::lengthy::exception());/throw CreateException(\1);/g'
Upvotes: 0
Reputation: 174706
You could try the below sed command.
sed 's/\bthrow some::lengthy::exception();/throw CreateException(some::lengthy::exception());/g' *.cpp
Add inline-edit -i
param to save the changes.
Upvotes: 0