|
From: Deepu on 23 Feb 2007 12:27 Hi All, I am trying to replace a word in a line with a different word. Example: File1: THIS IS AN ERROR TEST THIS IS A TEST THIS IS NOT A TEST I need to go through this file and check for ERROR in any line and replace with FAIL. Please help me on this. Code: #!/usr/local/bin/perl $testFile = "File1"; open (FH, "$testFile") || die; while (<FH>) { chomp; if ($_ =~ /ERROR/) { print "$_\n"; ## I get the line with ERROR here } } Thanks
From: J. Gleixner on 23 Feb 2007 12:40 Deepu wrote: > Hi All, > > I am trying to replace a word in a line with a different word. > > Example: > > File1: > THIS IS AN ERROR TEST > THIS IS A TEST > THIS IS NOT A TEST > > I need to go through this file and check for ERROR in any line and > replace with FAIL. > > Please help me on this. > > Code: > > #!/usr/local/bin/perl > > $testFile = "File1"; > > open (FH, "$testFile") || die; Include why. open( my $fh, '<', $testFile ) or die "Can't open $testFile: $!"; > > while (<FH>) { while( <$fh> ) { > chomp; That's probably not needed. > if ($_ =~ /ERROR/) { if( /ERROR/ ) { > print "$_\n"; ## I get the line with ERROR here s/ERROR/FAIL/g; print; > } > } close $fh; That will print the line, that used to contain ERROR, and now contains FAIL, to STDOUT. If you want to change it in the file. perldoc -q 'How do I change one line' How do I change one line in a file/delete a line in a file/insert a line in the middle of a file/append to the beginning of a file? Use the Tie::File module, which is included in the standard distribution since Perl 5.8.0. For information on how to use that module: perldoc Tie::File
From: Deepu on 23 Feb 2007 12:51 Thanks for the reply..how can i pass search & replace strings as arguments to the script
From: Brian McCauley on 23 Feb 2007 13:03 On Feb 23, 5:51 pm, "Deepu" <pradeep...(a)gmail.com> wrote without adequate context: [ please don't do that ] > Thanks for the reply..how can i pass search & replace strings as > arguments to the script Command line arguments to a Perl script are placed in the special array variable @ARGV. Be aware, however, that in the solution given earlier in this thread 'ERROR' is being treated as a regular expression _not_ a plain string. s/\Q$ARGV[0]/$ARGV[1]/g; Or slightly more long winded but maybe clearer: # Ouside the loop my ($search,$replace) = @ARGV; # Inside the loop s/\Q$search/$replace/g;
From: J�rgen Exner on 23 Feb 2007 13:15 Deepu wrote: > Thanks for the reply.. What reply? I don't see any. What are you talking about? > how can i pass search & replace strings as > arguments to the script The same way as you would pass any other argument to any other program: you just type them on the command line after the command or script name. jue
|
Next
|
Last
Pages: 1 2 3 Prev: here is the famous godwin script, donated to the usenet populous! Next: Text::CSV and Mysql |