Mak_Thareja
Mak_Thareja

Reputation: 177

Perl: Need to match a pattern

I have a variable containing a string.

$name="mak -o create.pl -n create.txt";

Now I want to match a pattern in which I can get the value as create.pl which will always be followed by -o. That is , this is mandatory that this will occur always like this "-o create.pl" But instead of "create" there could be any name like this but the extension will always be ".pl"

$name="mak -o string.pl -n create.txt"; # or it could be
$name="mak -o name.pl -n create.txt";

Upvotes: 1

Views: 73

Answers (4)

Nikhil Jain
Nikhil Jain

Reputation: 8332

Using split :Dont need to worried about script name, split will take care of it.

use strict;

my $name="mak -o name.pl -n create.txt";

my $test = join( " ", (split /\s+/, $name)[1,2] );

print $test;

output:

-o name.pl   

Upvotes: 0

Nate
Nate

Reputation: 1921

Try splitting the variable by space.

my $name="mak -o name.pl -n create.txt";

my @cmd = split (/\s+/, $name);

for (my $i = 0; $i <@cmd; $i++) {
    if ($cmd[$i] eq "-o") {
        print $cmd[$i+1];
        last;
    }
}

Upvotes: 1

Vijay
Vijay

Reputation: 67211

`/-o ([^\s]*)\s/`

Above will do :

> echo "mak -o create.pl -n create.txt" | perl -lne 'm/-o ([^\s]*)\s/;print $1'
create.pl

Upvotes: 1

Aziz Shaikh
Aziz Shaikh

Reputation: 16524

Try this regular expression:

/-o\s(.*?)\.pl/

$1 will have the matched name.

Upvotes: 0

Related Questions