I have written down a simple perl program to replace a string from a word file. My script does'nt seem to work. Any pointers to make it work will be appreciated. The code is given below.
#!/usr/bin/perl
while (<>) {
open(FILE,$_);
while (<FILE>) {
s/This/I did it/g;
}
close(FILE);
}
I run the script from the command line as:
perl myscript.pl inputfile.txt
What is your expected results?
This you can do from the command line, from a shell script, or you can put it in a perl script.
$1 is whatever you pass to the script.
Put this command in a file called replace and run it like this
#replace inputfile.txt
This searches the file $1, ($1 is what you pass to the replace script) it looks for the word 'This' and replaces in with 'I did it' and prints it to a new file called /tmp/newinputfile.txt.
perl -e 'while(<>){if(/This/){$="I did it\n"} print "$"}' $1 > /tmp/newiputfile.txt
Hope this helps
-X
The file, "input.txt" contains the following string:
This is the text I wrote
To start with, I want to replace the word "This" with "I did it".
Here.....This is even better....Since the source file and destination file are the same, consider doing something like this.
commandline
perl -pi -w -e 's/This/I did it/g;' inputfile.txt
script
perl -pi -w -e 's/This/I did it/g;' $1
Run script from commandline.
#myscript.pl inputfile.txt
This is sweet...
-X
I noticed that I the file specified on the command line will be read line by line. I modified the script as below but it still does'nt work. Can there be some problem with file permissions?
#!/usr/bin/perl
while (<>) {
s/This/I did it/g;
}
#!/usr/bin/perl -i
while (<>) {
s/This/I\ did\ it/g;
print;
}
perl -i myscript.pl input.txt