http://www.perlmonks.org?node_id=1197384


in reply to sed command with variable in perl

Long (very long) version. Use regexen. File process_file_1.pl:

use warnings; use strict; die "usage: perl $0 file.name \n" unless @ARGV; my $filename_in = shift; print "processing '$filename_in' \n"; my $filename_out = "$filename_in.new"; open my $fh_in, '<', $filename_in or die "opening '$filename_in': $! +"; open my $fh_out, '>', $filename_out or die "opening '$filename_out': $ +!"; my $sol1 = 'my new stuff'; while (<$fh_in>) { s{ (SOL) [^\n]* }{$1 $sol1}xmsg; print $fh_out $_ or die "writing '$filename_out': $!"; } close $fh_in or die "closing '$filename_in': $!"; close $fh_out or die "closing '$filename_out': $!"; rename $filename_in, "$filename_in.bak" or die "renaming '$filename_in +': $!"; rename $filename_out, $filename_in or die "renaming '$filename_ou +t': $!";
This has all the bells and whistles. Shorter versions (including a one-liner) are possible depending on your exact needs. BTW: What version of Perl are you using?

Usage session:

c:\@Work\Perl\monks\samira_saber>dir Volume in drive C is Acer Volume Serial Number is 9480-355B Directory of c:\@Work\Perl\monks\samira_saber 08/14/2017 05:23 PM <DIR> . 08/14/2017 05:23 PM <DIR> .. 08/14/2017 05:04 PM 759 process_file_1.pl 08/14/2017 04:40 PM 46 topol1.au 08/14/2017 04:40 PM 46 topol1.top 3 File(s) 851 bytes 2 Dir(s) 24,485,937,152 bytes free c:\@Work\Perl\monks\samira_saber>fc topol1.au topol1.top Comparing files topol1.au and TOPOL1.TOP FC: no differences encountered c:\@Work\Perl\monks\samira_saber>type topol1.top not so SOLITARY SOLUTION SOLVE the problem c:\@Work\Perl\monks\samira_saber>perl process_file_1.pl topol1.top processing 'topol1.top' c:\@Work\Perl\monks\samira_saber>dir Volume in drive C is Acer Volume Serial Number is 9480-355B Directory of c:\@Work\Perl\monks\samira_saber 08/14/2017 05:26 PM <DIR> . 08/14/2017 05:26 PM <DIR> .. 08/14/2017 05:04 PM 759 process_file_1.pl 08/14/2017 04:40 PM 46 topol1.au 08/14/2017 05:26 PM 61 topol1.top 08/14/2017 04:40 PM 46 topol1.top.bak 4 File(s) 912 bytes 2 Dir(s) 24,485,937,152 bytes free c:\@Work\Perl\monks\samira_saber>type topol1.top not so SOL my new stuff SOL my new stuff SOL my new stuff c:\@Work\Perl\monks\samira_saber>fc topol1.au topol1.top.bak Comparing files topol1.au and TOPOL1.TOP.BAK FC: no differences encountered

Please see perlre, perlretut, and perlrequick for (lots and lots of) regex info. See also perlop (update: specifically, the Regexp Quote-Like Operators section) for discussion of the  s/// substitution operator.


Give a man a fish:  <%-{-{-{-<