Tuesday, 7 February 2023

Regular expression to match a line that doesn't contain a word

 


In this article, we will explore how to use regular expressions with Perl to match lines that do not contain a specific word. We will provide a code example that demonstrates how to achieve this.


#!/usr/bin/perl

use strict;

use warnings;


my $word_to_exclude = 'hede';


while (my $line = <>) {

    chomp $line;

    if ($line !~ /$word_to_exclude/) {

        print "$line\n";

    }

}


Explanation

The code provided above demonstrates how to use regular expressions with Perl to match lines that do not contain a specific word. Here's a breakdown of the code:

We start by declaring the word we want to exclude from the lines as a variable named $word_to_exclude. In this case, the word is 'hede'.

We then enter a while loop that reads each line from the input.

The chomp function is used to remove the trailing newline character from each line.

The if statement checks if the line does not match the regular expression /hede/. The !~ operator is used to negate the match.

If the line does not contain the word 'hede', it is printed using the print statement.

The loop continues until all lines have been processed.

To use this code, save it to a file (e.g., exclude_word.pl) and make it executable using the command chmod +x exclude_word.pl. Then, you can run it by providing the input file as an argument:


./exclude_word.pl input.txt

Replace input.txt with the path to your input file.

Labels: , ,

0 Comments:

Post a Comment

Note: only a member of this blog may post a comment.

<< Home