Pattern Matching in UNIX

Hello,

I have a pattern like "XXXXXX XXXXXX" which i need to make search in a input file and Replace the matched pattern to a another pattern.

This is the code i tried ..

#!/usr/bin/perl
print "Enter a File name :";
chomp ($file = <STDIN>);
print "\n Searching file :";
if (system ("ls $file")==0)
{
print "File Found\n";

$lines = `wc -l $file`;
@personal = split(/ /, $lines);
$lines = @personal[0];

print "Total number of lines in the file = $lines \n";

print "Enter the pattern to search :";
chomp ($pattern = <STDIN>);
print "\n";
# to search the no of words (pattern search)
$abc=`grep $pattern $file | wc -l`;
print "Total number of results found $abc \n";
print "here are the results ...\n";
system("grep $pattern $file");
}
else{
print "File not Found\n";
}

This code works where i input a pattern without spaces like "MAX",
But when i give a Pattern like this "MAX XAM", the script errors out.

I tried to put "/s" also, its erroring out.

How can i search a pattern which is embeded with a space between two words.

Can any one please help.

Thanks

Rahul

You need to properly quote variables with spaces or other special characters in them.

If you want to use Perl, it's rather weird to not do the actual matching in Perl also. Running the grep twice just because you want the number of matches first is also ... intriguing. Here, I cannot resist.

#!/usr/bin/perl
print "Enter a File name :";
chomp ($file = <STDIN>);
print "\n Searching file :";
if (-e $file)
{
    print "File Found\n";

    $lines = `wc -l < $file`;
    chomp $lines;

    print "Total number of lines in the file = $lines \n";

    print "Enter the pattern to search :";
    chomp ($pattern = <STDIN>);
    print "\n";
    # to search the no of words (pattern search)
    $abc=`grep "$pattern" $file`;
    $count = () = $abc =~ m/\n/g;
    print "Total number of results found: $count\n";
    print "here are the results ...\n$abc\n";
}
else{
    print "File not Found\n";
}

Hello Era,

Thanks for the corrections, it really worked.

I am just beginner to scripting, that why iam rusty.

but your suggestions really helped me, will correct the mistakes.

Thanks

Rahul