in reply to Re: Print word from text file that is not an exact match
in thread Print word from text file that is not an exact match

Hi NetWallah, Thanks so much for your quick response and a solution that works! If you can please take a look at the following code and let me know what I am doing wrong I would greatly appreciate it. If I can get this to work then I will be able to accomplish what I need to do for my first perl script. I think I am close to getting this to worK? Thanks,
my $file = "computers.txt"; print "-->>Paste computer name(s) here, press enter key, then ctrl-D k +eys<<--\n"; @computers = (<STDIN>); foreach (@computers) { open FILE, "$file"; while ($line=<FILE>){ if (my ($name) = $line=~/(@computers[\.\w]*)/){ print "name\n"; else print "no match found\n"; close FILE, "$file"; } } }
Regards, Tony

Replies are listed 'Best First'.
Re^3: Print word from text file that is not an exact match
by poj (Abbot) on Jun 09, 2018 at 18:27 UTC
    Paste computer name(s) here, press enter key,

    Where are you copying the names from, is is another text file ? If so, please show example

    poj
      Hi poj, Yes I am copying the names from another text file that looks something like this: Server1 Server2 Server3 Regards, Tony

        There are ways to avoid repeat searches of each line but this should get you started.

        #!/usr/bin/perl use strict; my $count = 0; my $namefile = $ARGV[0] || 'names.txt'; # default if no argument # names.txt #ServerName1 #ServerName2 # get list of computers to search for my @computers; open FILE,'<',$namefile or die "Could not open $namefile : $!"; while (<FILE>){ chomp; s/^\s+|\s+$//g; # trim spaces next unless /\S/; # skip blank lines push @computers,$_; } close FILE; my $file = "computernames.txt"; # computernames.txt #<Answer type="string">ServerName1.FD.net.org</Answer> #<Answer type="string">ServerName2.FD.net.org</Answer> #<Answer type="string">ServerName3.FD.net.org</Answer> # search text file open IN, '<',$file or die "Could not open $file : $!"; while (my $line = <IN>){ # repeat line search for each computer foreach my $search (@computers) { if ( my ($name) = $line =~ /($search[\.\w]*)/ ){ print "Name ; $name\n"; ++$count; } } } close IN; # result if ($count){ print "$count matches\n"; } else { print "No matches found\n"; }
        poj