April 15th, 2013, 05:03 AM
Replace a string in a file from perl script!
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.
April 15th, 2013, 01:43 PM
You could do that with a Perl one-liner launched from the command line:
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.
perl -pi -e 's/\r/ /g' my_file.txt
If you are using Windows, then change apostrophes to double quotes:
Within a larger Perl program, assuming your line is in the $line variable, do it this way:
perl -pi -e "s/\r/ /g" my_file.txt
And if you want to change every occurrence (in your line) of "foo" by "bar":
April 16th, 2013, 06:49 AM
Thank you very much for your reply. Yes it is working.