Hi
I try to Search for xp_cmdshell string in log.txt file but i got error?

my $file = "c:/logdata.txt";
open (IN,$file) or die "Can't read $file: $!";
my $tag = "xp_cmdshell";
open(IN,"<",$file) || die "could not open $file: $!\n";
while (<IN>) {
    if (grep(/$tag/,$_)) {
    #Do something
  }
}
Close(file);

Recommended Answers

All 4 Replies

Hi tony75,

1.What error message are you getting.
2.Check your filehandle "IN" you used. You can't be reading FROM and writing TO the same filehandle, like you are doing.
3.Also use a 3-arugment for open function. like

open my $fh,'<',$file_to_read or die "can't open file: $!";
   while(<$fh>){
     ...
   }
 close $fh or die "can't open file: $!";

4.Use lexically scoped filehandle like $fh in the code above.

Please see perldoc -f open frm your CLI
Hope this helps

Thanks Sir,
But
How can I navigate to my log.txt file on my C:\ driver ?

my $file = shift || die " Enter file name \n";
die "File not found!\n" unless (-e $file);
my $tag = "xp_cmdshell";
open(FH,"<",$file) || die "could not open $file: $!\n";
while (<FH>) {
    if (grep(/$tag/,$_)) {
    #Do something
  }
}
Close(FH);

Hi tony75,
Yes that should work, but you can also do like so:

#!/usr/bin/perl
use warnings;
use strict;

my $filename = "";
do {
    print "Enter  file name: ";
    ## get name from the user from CLI
    chomp( $filename = <STDIN> );
    warn "File not Found\n" if !-e $filename;
} while ( $filename eq '' or !-e $filename );

my $tag = "xp_cmdshell";

open my $fh, "<", $filename or die "could not open $filename: $!\n";
while (<$fh>) {
    chomp;
    if ( grep( /$tag/, $_ ) ) {

        #Do something
    }

}
close($fh) or die "can close file: $!";

It's good practice to always use a lexical scope filehandle like I did, than using a BAREWORD like FH, which is global as filehandles. Then always check for the return of close function just like open function.

Check the usage of the do/while, which enable the user to provide a "workable" filename from the CLI. Please note that, I didn't include a way out, except a correct filename is used. That you could do.
There are more than one way do it though.

You could also check these modules Getopt::Long or Getopt::Std. Just use perldoc Getopt::Long

Wonderful.
Thank you very much.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.