How to grep string and assign it to a variable in Perl

venkat Source

I have a file with the below details;

file name: allappsclus

cont:i-02dd208bf1d81c254
rs:i-0098ad0b59b7fe7cf

I want to use the value for i-XXX"= in associated cont name and assign it to another variable.

If run my code and get an output it is

test-1.1.0.0
1insideif-CNS
use strict;
use warnings;

use Data::Dumper;

my $jupyter    = 0;
my $controller = 0;
my $rstudio    = 0;
my $zeppelin   = 0;

my $fh= '/tmp/allappsclus';

open my $fh2, '<', $fh  or die "Cannot open file: $!\n";

while ( <$fh2> ) {

    if ( $_ =~ /jup/ ) {
        $jupyter = 1;
    }
    elsif ( $_ =~ /con/ ) {
        $controller = 1;
    }
    elsif ( $_ =~ /rs/ ) {
        $rstudio = 1;
    }
    elsif ( $_ =~ /zep/ ) {
        $zeppelin = 1;
    }
}

print "test-$rs.$con.$jup.$zep\n";

if ( $zepeq '0' && $jup eq '0' && $con eq '1' && $rs eq '1' ) {
    print "insideif-CNS";
}
else {
    print "do nothing";
}

close $fh;
close $fh2;

Now I want to print the value i-02dd208bf1d81c254 instead of CNS in the output.

perl

Answers

answered 3 months ago SARAVANAN #1

$myStr = "cont:i-02dd208bf1d81c254 rs:i-0098ad0b59b7fe7cf";

if ($myStr =~ /cont:([^ ]+)/) # match the full pattern with the value you required
{
   $controller=1;
   $cont = $1;    # assign required value to a variable
}
print $cont;      # print the variable

This might work for you.

comments powered by Disqus