Smart search / replace with regular expression and back reference
As a developer, I had to search and replace in my source code within single file or whole project. Occasionally the search and replace could involve regular expression and back reference to groups found in regular expression.
For example:
I need to replace
equalTo("value 1234") to "value 1234"
equalTo("value 5678") to "value 5678"
These smart search and replace needs regular expression and back reference to the group.
The following is an example to perform it through IDE like IntelliJ IDEA or Microsoft Visual Studio Code (VS Code)
Search Reg Ex: equalTo\("(.*)"\)
Replace Reg Ex: "$1"
The same can be performed using sed as shown below
For single file:
sed -i '' -E 's/equalTo\("(.*)"\)/"\1"/g' some_file.txt
For multiple files using find and xargs:
find . -name "some_file*.txt" -print0 | xargs -0 -I {} sed -i '' -E 's/equalTo\("(.*)"\)/"\1"/g' {}
For example:
I need to replace
equalTo("value 1234") to "value 1234"
equalTo("value 5678") to "value 5678"
These smart search and replace needs regular expression and back reference to the group.
The following is an example to perform it through IDE like IntelliJ IDEA or Microsoft Visual Studio Code (VS Code)
Search Reg Ex: equalTo\("(.*)"\)
Replace Reg Ex: "$1"
The same can be performed using sed as shown below
For single file:
sed -i '' -E 's/equalTo\("(.*)"\)/"\1"/g' some_file.txt
For multiple files using find and xargs:
find . -name "some_file*.txt" -print0 | xargs -0 -I {} sed -i '' -E 's/equalTo\("(.*)"\)/"\1"/g' {}
Comments
Post a Comment