Once you are happy with the content of the filename.out file, you can add code to delete or rename in input file and rename your output file to the original source file, if needed (or to rename the input file before hand and write directly to an output file having the name of the input file, if you prefer).use strict; use warnings; my $infile = "filename.txt"; my $outfile = "filename.out"; open my $IN, "<", $infile or die "Could not open file $infile : $!"; open my $OUT, ">", $outfile or die "Could not open file $outfile : $!" +; my $step_num = 0; while (<$IN>) { if (/-----------step [\d]\./){ $step_num ++; s/-----------step \d\./-----------step $_\.$step_num/; } print $_ $OUT; } close $IN; close $OUT;
Although there are some work-around solutions, in general you can't read from and write to the same free-format file, and this is essentially true in almost any programming language.
The two main solutions are the following:
1. open the input file, load it all into memory (e.g. in an array of lines), close the file, modify its content in memory, open the same file in write mode (which will clutter its original content), and print the result into it (this is basically what's going on behind the scenes when you open a text file with your favorite editor or with a word processor);
2. Read the file and write to another file (as suggested in my code above), and do the necessary house cleaning (renaming the files) afterward or possibly before (this is what the -i command-line option suggested by AppleFritter if essentially doing behind the scene).
There are a few "more advanced" solutions, such as using tieed variables (i.e. doing even more complicated things behind the scene), but I would suggest that you stay with either of the two simple solutions described above for the time being.
As an additional point, please note that I made a few other changes to your code, adding the use strict; use warnings; pragmas (you should always have them, except possibly for one-liners), and changing the syntax for opening a file to the "3-argument" syntax, this is not absolutely necessary, but this is considered to be good practice nowadays. This "new" syntax was introduced, I believe, with Perl 5.6, so that's more than ten years ago.
In reply to Re: Modifying a file using RegEx
by Laurent_R
in thread Modifying a file using RegEx
by gotsilk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |