Skip to content
Advertisement

grep case-insensitively for a string in a text file

I’m writing a Perl script but I don’t get a part of it.

There’s a text file with host names, one per line.

I need to search a second file with host names (a blacklist) for the hostname read from the first one. To be sage the search should be done case insensitive.

My first approach was using the Perl grep, but I read about it and it seems not quite usable for what I needed it to. So I thought about using the shell grep.

As far as I know, it could be executed with system, qx, backticks and open.

I decided to use system, so that I can get the exit status code of the grep and use it in a if statement to do the rest of the work the script is intended to. My code looks like this (test script with the grep):

use strict;
use warnings;

my $blacklist_server = "de9899svc";
my $server = undef;
my $exit_value = undef;

 open(SERVERLISTE,"/home/ansible/serverscan/scan_results/serverliste_22.02.17.txt") or die "$!";

OUTER: while (<SERVERLISTE>) {
    $server = $_;

    system("grep -i '$server' /home/ansible/serverscan/black.list");
    $exit_value  = $? >> 8;
    print "$exit_valuen";
}

close SERVERLISTE;

The problem is, that $exit_value is always 1, regardless of whether the host names match or not. So can somebody please tell me what I’m missing 🙂

Advertisement

Answer

 grep -iF -f blacklist serverlist

The above command prints all lines in serverlist that match any of the lines in blacklist case insensitively.

If you want to remove lines from serverlist that matches any line in blacklist use:

 grep -viF -f blacklist serverlist

You can grab output inside perl using back ticks.

$not_blacklisted=`grep -viF -f blacklist serverlist`;

More readable commands:

grep --ignore-case --fixed-strings --file=blacklist serverlist

or

grep --invert-match --ignore-case --fixed-strings --file=blacklist serverlist

I tried this with GNU grep 2.25.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement