Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems with replacing first line of file using perl

Tags:

io

perl

I have a file that looks like this:

I,like
blah...

I want to replace only the first line with 'i,am' to get:

i,am
blah...

These are big files, so this is what I did (based on this):

open(FH, "+< input.txt") or die "FAIL!";
my $header = <FH>;
chop($header);
$header =~ s/I,like/i,am/g;
seek FH, 0, 0; # go back to start of file
printf FH $header;
close FH;

However, I get this when I run it:

i,amke
blah...

I looks like the 'ke' from like is still there. How do I get rid of it?

like image 642
jh314 Avatar asked Jan 31 '26 21:01

jh314


1 Answers

What I would do is probably something like this:

perl -i -pe 'if ($. == 1) { s/.*/i,am/; }' yourfile.txt

Which will only affect the first line, when the line counter for the current file handle $. is equal to 1. The regex will replace everything except newline. If you need it to match your specific line, you can include that in the if-statement:

perl -i -pe 'if ($. == 1 and /^I,like$/) { s/.*/i,am/; }' yourfile.txt

You can also look into Tie::File, which allows you to treat the file like an array, which means you can simply do $line[0] = "i,am\n". It is mentioned that there may be performance issues with this module, however.

like image 80
TLP Avatar answered Feb 03 '26 15:02

TLP