sed '$d' $file;
Using this command doesn't seem to work, as $
is a reserved symbol in Perl.
sed '$d' $file;
Using this command doesn't seem to work, as $
is a reserved symbol in Perl.
Don't know why are you using sed
into Perl. Perl itself have standard module to delete last line from a file.
Use the standard (as of v5.8) Tie::File
module and delete the last element from the tied array:
use Tie::File;
tie @lines, Tie::File, $file or die "can't update $file: $!";
delete $lines[-1];
The closest syntax seem to be:
perl -ne 'print unless eof()'
This will act like sed
, ie: without the requirement of reading the whole file into memory and could work with FIFO like STDIN
.
See:
perl -ne 'print unless eof()' < <(seq 1 3)
1
2
or maybe:
perl -pe '$_=undef if eof()' < <(seq 1 3)
1
2
perl -pe '
BEGIN {
chomp(my $first= <>);
print "Something special with $first\n";
};
do {
chomp;
print "Other speciality with $_\n";
undef $_;
} if eof();
' < <(seq 1 5)
will render:
Something special with 1
2
3
4
Other speciality with 5
perl -pe 's/^/Something... / if$.==1||eof' < <(seq 1 5)
will render:
Something... 1
2
3
4
Something... 5
Try this:
perl -pe 'BEGIN{$s=join"|",qw|1 3 7 21|;};
if ($.=~/^($s)$/||eof){s/^/---/}else{s/$/.../}' < <(seq 1 22)
... something like sed
command:
sed '1ba;3ba;7ba;21ba;$ba;s/$/.../;bb;:a;s/^/---/;:b' < <(seq 1 22)
#!/usr/bin/perl -w
use strict;
sub something {
chomp;
print "Something special with $_.\n";
}
$_=<>;
something;
while (<>) {
if (eof) { something; }
else { print; };
}
will give:
/tmp/script.pl < <(seq 1 5)
Something special with 1.
2
3
4
Something special with 5.
Hope you are trying to execute the 'sed' command from the middle of a perl script. I would recommend not to use this approach because it will work only in non-windows systems. Below is a perl'ish approach in which you can process first and last lines only rather than spending effort to delete file contents. Thank you.
Assuming "myfile.txt" as the input file:
open (FH, "<", "myfile.txt") or die "Unable to open \"myfile.txt\": $! \n";
$i = 1;
while(<FH>){
next if ($i++ == 1 or eof);
# Process other lines
print "\nProcessing Line: $_";
}
close (FH);
print "\n";
1;
myfile.txt -
# First line
This is the beginning of comment free file.
Hope this is also the line to get processed!
# last line
Result -
Processing Line: This is the beginning of comment free file.
Processing Line: Hope this is also the line to get processed!
This works for me, and it also removes unwanted empty lines at start and end.
use File::Slurp;
my $fileContent = read_file($csv_file);
my @lines = grep /\S/, split /\n/, $fileContent;
pop @lines;
$fileContent = join '', map "$_\n", @lines;
print $fileContent;
write_file($csv_file, $fileContent);