Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a String which has escape sequence inside a File using Perl?

Tags:

string

regex

perl

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' *
like image 293
Arunachalam Avatar asked Dec 21 '10 10:12

Arunachalam


People also ask

How do you replace a word in Perl?

Substitution Operator or 's' operator in Perl is used to substitute a text of the string with some pattern specified by the user.

How do you escape a special character in Perl?

Solution. Use a substitution to backslash or double each character to be escaped.

How do I escape a regular expression in Perl?

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: \\.


1 Answers

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:

  1. Escape the / in your pattern and replacement as:

    perl -pi -e 's/class\/students\/a/class1\/students1\/B/g' *
    
  2. 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.

like image 103
codaddict Avatar answered Nov 02 '22 17:11

codaddict