1

If I search for multiple search strings in grep : usually just do:

grep "search1\|search2" somefolder/*.txt

but, what if I have 100 or more search strings? Can I say like this:

grep "stringPattern.txt" somefolder/*.txt

where stringPattern.txt is a file containing a list of words I need to search in *.txt.

4

grep has the -f flag exactly for this, use:

grep -f patternfile somefolder/*.txt

Where in the patternfile the search patterns are separated line by line.

1

you can also work with other way around. if you have 100 patterns to search, then make a list what you don't want to search if it is less than 100 patterns and make it in a file1.txt

grep -vf file1.txt somefolder/*.txt
0

I've used perl to do this, as you can use perl to build a regex from an array:

#!/usr/bin/perl

use strict;
use warnings;
open ( my $searchfile, '<', "searchfile.txt" ) or die $!; 

my @search_for = <$searchfile>; 
close ( $searchfile );

my $search_regex = join ( "|", map {quotemeta} @search_for ); 
   $search_regex = qr/$search_regex/; 

print "Regex: $search_regex\n"; 

foreach my $file ( glob ( "somefolder/*.txt" ) ) { 
    open ( my $check, '<', $file ) or die $!; 
    while ( <$check> ) {
        print if m/$search_regex/;
    }
    close ( $check );
}

Note - quotemeta will escape metacharacters, which is good if you want to search for things including backslashes, spaces etc. But bad if you want to specify regex patterns.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.