In principle I am searching for a Perl equivalent for this sed command:
sed "/TIM_AM_ARGS=/ s/60/1440/" $EDIT_FILE > $TEMP_FILE
cp $TEMP_FILE $EDIT_FILE
I was wondering if it needs to be like this, or that there other, shorter, alternatives:
open (TIMENVFILE, "<$timenvfile") or die "Cannot open $timenvfile\n";
my @lines = <TIMENVFILE>;
close (TIMENVFILE);
open (NEWTIMENVFILE, ">$timenvfile") or die "Cannot open $timenvfile\n";
for (@lines) {
if ( $_ =~ m/TIM_AM_ARGS/ ) { $_ =~ s/60/1440/}
print NEWTIMENVFILE;
}
close (NEWTIMENVFILE);
you could write a perl one-liner for this. but if you are still interested in a perl script, here's one:
#!/usr/bin/perl
# sed_like.pl
use strict
use warnings;
my $filename = shift;
my $newfile = shift;
my @to_write;
open(FREAD, '<', $filename) or die "Failed to read file $filename : $!";
while (<FREAD>) {
if (m/TIM_AM_ARGS=/) {
s/60/1440/; # may be you need word boundaries here? like this: s/\b60\b/1440/
}
push(@to_write, $_);
}
close(FREAD);
open(FWRITE, '>', $newfile) or die "Failed to write file $newfile : $!";
print FWRITE @to_write;
close(FWRITE);
run this perl script as:
perl sed_like.pl file.txt newfile.txt
edit: and here's the one-liner:
perl -pi -e 's/60/1440/ if (/TIM_AM_ARGS=/)' file.txt
Thanks.
So the if statement is okay this way, I assume.
Just out of interest, what is the difference between a perl one-liner and a perl script ?
Basically a one-liner is a script consisting of one line (which can be run from the command line with perl -e).
Or ?
Most perl installations include s2p, a sed-to-perl translator. Here is an example:
#!/usr/bin/env bash
# @(#) s1 Demonstrate sed-to-perl translator, s2p.
echo
set +o nounset
LC_ALL=C ; LANG=C ; export LC_ALL LANG
echo "Environment: LC_ALL = $LC_ALL, LANG = $LANG"
echo "(Versions displayed with local utility \"version\")"
version >/dev/null 2>&1 && version "=o" $(_eat $0 $1) sed s2p
set -o nounset
echo
FILE=${1-data1}
echo " Data file $FILE:"
cat $FILE
echo
echo " Results:"
lines=$( s2p -f $FILE | wc -l )
echo " The s2p translator produced $lines lines of perl."
exit 0
producing:
% ./s1
Environment: LC_ALL = C, LANG = C
(Versions displayed with local utility "version")
OS, ker|rel, machine: Linux, 2.6.26-2-amd64, x86_64
Distribution : Debian GNU/Linux 5.0
GNU bash 3.2.39
GNU sed version 4.1.5
s2p - ( /usr/bin/s2p Jan 1 09:56 )
Data file data1:
/TIM_AM_ARGS=/ s/60/1440/
Results:
The s2p translator produced 122 lines of perl.
The biggest difference is that a script is generally saved as a file and a one-liner isn't.
A one-liner can actually be more than one line. They are generally used for simple tasks, where a script can do much more complex stuff than you would typically want to try using a one-liner.