Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl script to parse a text file and match a string

Tags:

perl

I'm editing my question to add more details

The script executes the command and redirects the output to a text file.

The script then parses the text file to match the following string " Standard 1.1.1.1"

The output in the text file is :

             Host Configuration
             ------------------

             Profile              Hostname
             --------             ---------

             standard             1.1.1.1
             standard             1.1.1.2

The code works if i search for either 1.1.1.1 or standard . When i search for standard 1.1.1.1 together the below script fails.

this is the error that i get "Unable to find string: standard 172.25.44.241 at testtest.pl

#!/usr/bin/perl
use Net::SSH::Expect;     
use strict;
use warnings;
use autodie;

open (HOSTRULES, ">hostrules.txt") || die "could not open output file";
my $hos = $ssh->exec(" I typed the command here  ");
print HOSTRULES ($hos);
close(HOSTRULES);

sub find_string
{
my ($file, $string) = @_;
open my $fh, '<', $file;
while (<$fh>) {
    return 1 if /\Q$string/;
}
die "Unable to find string: $string";
}

find_string('hostrules.txt', 'standard 1.1.1.1');
like image 265
user3587025 Avatar asked Jan 20 '26 07:01

user3587025


1 Answers

Perhaps write a function:

use strict;
use warnings;
use autodie;

sub find_string {
    my ($file, $string) = @_;
    open my $fh, '<', $file;
    while (<$fh>) {
        return 1 if /\Q$string/;
    }
    die "Unable to find string: $string";
}

find_string('output.txt', 'object-cache enabled');

Or just slurp the entire file:

use strict;
use warnings;
use autodie;

my $data = do {
    open my $fh, '<', 'output.txt';
    local $/;
    <$fh>;
};

die "Unable to find string" if $data !~ /object-cache enabled/;
like image 111
Miller Avatar answered Jan 22 '26 19:01

Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!