Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl Delete First Occurrence

Tags:

replace

perl

Okay so I want to delete the first occurrence of a string, let's say, "dog", in a file, and only the first occurrence. So if the file reads:

The dog was happy.
The dog liked to run.

The output would be

The was happy.
The dog liked to run.

I have the following code:

#!/usr/local/bin/perl

use warnings;
use strict;

my $file = $ARGV[0];
my $out = $ARGV[1];

open (IN, "<$file");
open (OUT, ">$out");
while(<IN>){
  s/dog/ /;
  print OUT $_;
}

close IN;
close OUT;

And it works, but instead of repacing just the first instance, it replaces all instances of the word. I thought I had to use the global modifier, g, to make it replace all instances? Why is it replacing all instances of the string I'm searching for? It's probably some simple error I'm not seeing.

like image 337
user1440061 Avatar asked Mar 05 '26 14:03

user1440061


2 Answers

It replaces the first instance each time you evaluate the operator, and you evaluate the operator for each line, so you replace the first instances in each line. Had you used /g, you would have been replacing all instances in each line.

my $seen;
while (<>) {
   ++$seen if !$seen && s/dog//;
   print;
}

Or as a one-liner:

perl -pe'++$seen if !$seen && s/dog//;' infile >outfile

You can add the file handles back in, but the above accepts a more standard and more flexible usage. To get the same effect as with your code, you just have to use

script.pl infile >outfile

instead of

script.pl infile outfile
like image 50
ikegami Avatar answered Mar 07 '26 12:03

ikegami


This can be achieved with a one-liner:

perl -0777 -pe 's/dog/ /' inputfile > outputfile

The -0777 switch will read the file as a single line, which will make your substitution work as you expected. This one-liner is equivalent to the program file:

$/ = undef; 
$\ = undef;
while (<>) {
    s/dog/ /;
    print;
}
like image 36
TLP Avatar answered Mar 07 '26 10:03

TLP



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!