user1597452
user1597452

Reputation: 93

How do I search a file then output a line with the keyword searched to a new file

I'm trying to search a large file with a keyword in perl, then output ALL the lines the keyword appears in, each into a new line.

Upvotes: 1

Views: 106

Answers (1)

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46778

The following will print all lines containing keyword to outputFile.txt. The input files are passed as arguments to the script.

findkeyword.pl

#!/usr/bin/perl
use strict;
use warnings;

open OUTPUT, ">outputFile.txt"; 
while (my $line = <>) {
     if($line =~ m/keyword/){
     print OUTPUT $line;
     }
}

Input:

./findkeyword.pl inputfile1 inputfile2 ...

Edit: As said by @Kenosis in the comments,

It might be better to use a lexically scoped $fh as file-handle like open(my $fh, ">", "outputFile.txt"). Reference: open()

If you are storing keyword in a variable, you might want to call quotemeta on it first, or enclose it in \Q...\E.

Upvotes: 4

Related Questions