#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    10
    Rep Power
    0

    Replace a string in a file from perl script!


    Hello Everyone,

    Is there any way which can replace a string in a file. I want something that can be included in the perl script.

    For example I have a file and i want to place the '^M' character at end of lines with th space.

    Many thanks in advance.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    830
    Rep Power
    496
    You could do that with a Perl one-liner launched from the command line:

    Code:
    perl -pi -e 's/\r/ /g' my_file.txt
    It replaces every occurrence of ^M (i.e. \r) by a space. The "i" option means that it will make the changes "in place", i.e. within the existing file without creating explicitly an extra file.

    If you are using Windows, then change apostrophes to double quotes:

    Code:
    perl -pi -e "s/\r/ /g" my_file.txt
    Within a larger Perl program, assuming your line is in the $line variable, do it this way:

    Perl Code:
    $line =~ s/\r/ /g;


    And if you want to change every occurrence (in your line) of "foo" by "bar":

    Perl Code:
    $line =~ s/foo/bar/g;
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2013
    Posts
    10
    Rep Power
    0
    Hi Laurent_R,

    Thank you very much for your reply. Yes it is working.
    Cheers

IMN logo majestic logo threadwatch logo seochat tools logo