editing text file in perl

K

king

I want to edit a perticular line in a 50 lines text file using perl.

File handle can be used for this.
But how can i edit a string present in say 20th line using perl
script.
 
B

Bart Van der Donck

king said:
I want to edit a perticular line in a 50 lines text file using perl.

File handle can be used for this.
But how can i edit a string present in say 20th line using perl
script.

#!perl
use strict;
use warnings;
my $file = 'file.dat';
my $line_counter = 0;
my $new_content;

open my $F, '<', $file || die "Cant open $file: $!";
flock($F, 1) || die "Cant get LOCK_SH on $file: $!";
while(<$F>) {
$line_counter ++;
if ($line_counter == 20) {
# do something on 20th line, eg. change it
$_ = "this is new content of line 20\n";
}
$new_content.= $_;
}
close $F || die "Cant close $file: $!";

# report
print $new_content;

Hope this helps,
 
I

Ian Wilson

Bart said:
king wrote:




#!perl
use strict;
use warnings;
my $file = 'file.dat';
my $line_counter = 0;
my $new_content;

open my $F, '<', $file || die "Cant open $file: $!";
flock($F, 1) || die "Cant get LOCK_SH on $file: $!";
while(<$F>) {
$line_counter ++;
if ($line_counter == 20) {
# do something on 20th line, eg. change it
$_ = "this is new content of line 20\n";
}
$new_content.= $_;
}
close $F || die "Cant close $file: $!";

# report
print $new_content;

I prefer to keep simple jobs simple :)
perl -pi -e 'if ($.==20) {s/^.*$/new content for line 20/;}' file.dat
or
perl -pi -e '($. == 20) && s/^.*$/new content for line 20/;' file.dat
 
G

Gunnar Hjalmarsson

Ian said:
I prefer to keep simple jobs simple :)
perl -pi -e 'if ($.==20) {s/^.*$/new content for line 20/;}' file.dat
or
perl -pi -e '($. == 20) && s/^.*$/new content for line 20/;' file.dat

'short' ne 'simple'
 
Joined
Oct 16, 2012
Messages
2
Reaction score
0
Help me

When i try to execute the following command (perl -pi -e 'if ($.==20) {s/^.*$/new content for line 20/;}' file.dat), I get this error message.
"Substitution replacement not terminated at -e line 1."

Kindly guide me with this.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top