how to replace a String inside a File using perl ?
perl -pi -e 's/Arun/Brun/g' *
this worked fine for me
but when i tried to change class/students/a
to class1/students1/B
it throws error how to solve this problem ..i tried adding back slash (\
) before every (/
) but it didn't help
perl -pi -e 's/class/students/a/class1/students1/B/g' *
Substitution Operator or 's' operator in Perl is used to substitute a text of the string with some pattern specified by the user.
Solution. Use a substitution to backslash or double each character to be escaped.
Because backslash \ has special meaning in strings and regexes, if we would like to tell Perl that we really mean a backs-slash, we will have to "escape" it, by using the "escape character" which happens to be back-slash itself. So we need to write two back-slashes: \\.
You are using /
as regex delimiter.
There are /
even in your pattern and replacement. You need to somehow ensure that these /
should not be treated as delimiter.
You have two options:
Escape the /
in your pattern and replacement as:
perl -pi -e 's/class\/students\/a/class1\/students1\/B/g' *
Or use a different delimiter:
perl -pi -e 's#class/students/a#class1/students1/B#g' *
Method 2 is preferred as it keeps your regex short and clean.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With