in reply to Re^4: Search and delete lines based on string matching
in thread Search and delete lines based on string matching
Ah, you specified that words had to be removed, not tokens that could be part of a word. For the token 'bin' which should be removed:
- foobin
- binary
- bin1
To:my $pattern = '\b(?:' . join('|', @tokens) . ')\b';
If you only want to match words that start with 'bin', and are followed only by non-alpha characters, then this:my $pattern = join('|', @tokens);
A revised copy that handles the deletion of tokens with a purely line based input:my $pattern = '^(?:' . join('|', @tokens) . ')[^a-zA-Z]*$';
#!/usr/local/bin/perl use strict; use warnings; if (@ARGV != 3) { print "Usage: $0 <pattern file> <input file> <output file>\n"; exit; } my ($pattern_filename, $source_filename, $dest_filename) = @ARGV; open my $pattern_fh, '<', $pattern_filename or die "Failed to open $pa +ttern_filename: $!"; my @tokens = (); while (my $line = <$pattern_fh>) { chomp $line; push @tokens, $line; } my $pattern = '^(?:' . join('|', @tokens) . ')[^a-zA-Z]*$'; print "Search pattern: $pattern\n"; open my $infile, "<", $source_filename or die "Failed to open $source +_filename: $!"; open my $outfile,">>", $dest_filename or die "Failed to open $dest_f +ilename: $!"; while(my $line = <$infile>) { print "input : $line"; if ($line =~ /$pattern/) { next; } print "output: $line"; print $outfile $line; } close($infile); close($outfile);
In Section
Seekers of Perl Wisdom