Please show me how to make substitution over the contents of a file in a perl script.
In a perl script, the core part of substitution operation is
s/FINDPATTERN/REPLACEPATTERN/g;
However, I cannot figure out how to make the substitution occur over the contents of a file. The following perl script failed by syntax error.
#!/usr/bin/perl
use strict;
use warnings;
s/FINDPATTERN/REPLACEPATTERN/g FILE;
The substitution over the contents of a file involves reading and writing of the file. I do not know how to connect the substitution to the reading and writing of a file.
$
$ # display the data file
$ cat -n data_file
1 this is line 1
2 this is line 2
3 i want to substitute this => ~ <= by that => # <=
4 at multiple places => abc~ def~ghi ~~jkl ~~
5 in multiple lines => ~
6 and here ~
7 and here as well ~
8 this is line 8
9 and this is the last line...
$
$ # show the Perl program to update the data file
$ cat -n update_data_file.pl
1 #!/usr/bin/perl -w
2 use strict;
3 my $old = "data_file"; # the data file
4 my $new = "data_file.new"; # a new/temporary file, which will be moved to $old
5 open(OLD, "<", $old) or die "can't open $old: $!";
6 open(NEW, ">", $new) or die "can't open $new: $!";
7 while (<OLD>) {
8 s/~/#/g; # globally replace ~ by # in the current line
9 print NEW $_; # print the updated line to new/temporary file
10 }
11 close(OLD) or die "can't close $old: $!";
12 close(NEW) or die "can't close $new: $!";
13 # back up the $old file and rename the new/temporary file to $old
14 rename($old, "$old.orig") or die "can't rename $old to $old.orig: $!";
15 rename($new, $old) or die "can't rename $new to $old: $!";
$
$ # run the Perl program
$ perl update_data_file.pl
$
$ # check the updated data file
$ cat -n data_file
1 this is line 1
2 this is line 2
3 i want to substitute this => # <= by that => # <=
4 at multiple places => abc# def#ghi ##jkl ##
5 in multiple lines => #
6 and here #
7 and here as well #
8 this is line 8
9 and this is the last line...
$
$ # check the backup file
$ cat -n data_file.orig
1 this is line 1
2 this is line 2
3 i want to substitute this => ~ <= by that => # <=
4 at multiple places => abc~ def~ghi ~~jkl ~~
5 in multiple lines => ~
6 and here ~
7 and here as well ~
8 this is line 8
9 and this is the last line...
$
$