I want to check existence of server name taken from one file in another one. The idea is that second file holds multiple lines with server name + additional info in each.
so the output for the example name "server01" is
server01
server01
server01
i want to have it only once in output xls file for each name that exist in both files of course.
The program so far is:
#!/usr/bin/perl -w
use Spreadsheet::WriteExcel;
#OPEN FILES
open(FILE, "CEP06032012.csv") or die("Unable to open CEP file");
#CEP_file = <FILE>;
close(FILE);
open(FILE, "listsystems_temp") or die("Unable to open listsystems file");
#listsystems_file = <FILE>;
close(FILE);
#XLS properties
my $workbook = Spreadsheet::WriteExcel->new('report.xls');
my $worksheet_servers = $workbook->add_worksheet();
#MAIN
my $r = 0;
foreach my $lines(#CEP_file){
my #CEP_file = split ";", $lines;
my $server = $CEP_file[8];
foreach my $lines2(#listsystems_file){
if ($lines2 =~ m/.*$server.*/i && $server ne ""){
print "$server \n";
#print "$lines2 \n";
$worksheet_servers->write($r, 0, "$server");
$r++;
}
}
}
exit();
any ideas how to change it?
Try this. This will skip multiple occurance of $server, keep only one.
my %seen;
foreach my $lines2(#listsystems_file){
next if $seen{$server};
if ($lines2 =~ m/.*$server.*/i && $server ne ""){
print "$server \n";
#print "$lines2 \n";
$worksheet_servers->write($r, 0, "$server");
$r++;
$seen{$server} = 1;
}
}
Related
So I'm having a problem trying to split a variable that has the complete path to a directory. I want to fetch the files under 'logs' directory of this path:
'/nfs/fm/disks/fm_mydiskhere_00000/users/me/repotest/myrepo/tools/toolsdir/logs/*';
and in my Perl script, I have a variable that contains this path: '$log_file'. When I print '$log_file', it contains the entire path; I want to go to the last directory 'logs' and fetch the files under it. By the way, this complete path is in a separate configuration file that is being read by my Perl script this way:
sub read_file {
my ($log_file) = shift(#_);
info ("Using file : $log_file");
my $fh = new FileHandle ("$log_file");
printError ("Could not open this file : '$log_file' - $!") unless defined $fh;
my $contents;
{
local $/ = undef;
$contents = <$fh>;
}
$fh->close();
eval $contents;
if ($#) {
chomp $#;
my $msg = "BAD (perl) syntax in file:\n\n$#\n";
if ( $msg =~ /requires explicit package name/ ) {
$msg .= "\n -> A 'requires explicit package name' message means".
" a NON-VALID variable name was found\n";
}
die "Error: $msg\n\n";
}
return 1;
}
And I'm using variable $log_file in another subroutine this way:
my $fh = read_file ($log_file);
if ($log_file eq "abc.txt"){
while (my $line = <$fh>) {
#do something
}
}
Can anybody help me here, please? Am I missing something or using $log_file in the wrong way?
Thanks in advance!
Try:
my #files = glob($log_file);
use Data::Dumper;
print Dumper(\#files);
I wrote a script to match a pattern and return a statement for a file
#!/usr/bin/perl
use strict;
use warnings;
my $file = '/home/Sidtest/sid.txt';
open my $info , $file or die " Couldn't open the $file:$!";
while( my $line = <$info>) {
if ($line =~ m/^#LoadModule ssl_module/) {
print "FileName =",$file," Status = Failed \n";
}
elsif ($line =~ m/^LoadModule ssl_module/) {
print "FileName =",$file," Status = Passed \n";
}
}
close $info;
So now I am trying to modify this script to work for multiple files under the same directory. I haven't been able to do that successfully. Can anyone please help in how I can make it work for any number of files in a directory.
This will read every file in ./directory and foreach file, print out each line.
The print statement can be altered to print if /match/, or whatever you want:
my #dir = <directory/*>;
foreach my $file (#dir){
open my $input, '<', $file;
while (<$input>){
print "PASS: $_\n" if m/^#LoadModule ssl_module/;
[...]
}
}
The variable #ARGV contains a list of arguments sent to the script when started. Loop through #ARGV and call the script with the files you want to process:
#!/usr/bin/perl
use strict;
use warnings;
foreach my $file (#ARGV) {
open my $info , $file or die " Couldn't open the $file:$!";
while( my $line = <$info>) {
if ($line =~ m/^#LoadModule ssl_module/) {
print "FileName =",$file," Status = Failed \n";
}
elsif ($line =~ m/^LoadModule ssl_module/) {
print "FileName =",$file," Status = Passed \n";
}
}
close $info;
}
# process all files *.txt in your dir: ./myscript.pl /home/Sidtest/*.txt
Check perldoc perlrun, and look at the -p and -n parameters. Essentially, they treat your script as if it were the contents of a loop over stdin, where stdin is generated by iterating through the files supplied on the command line. The name of the file currently-being-processed can be accessed using the $ARGV variable.
So, you might go for an approach where your whole script looks more like this, using the -n param, where $_ contains the current line.:
if ( m/^#LoadModule ssl_module/) {
print "FileName =",$ARGV" Status = Failed \n";
} elsif (m/^LoadModule ssl_module/) {
print "FileName =",$ARGV," Status = Passed \n";
}
If I want to find in this file all instances of the words USER and PASS and then put the number of times they appear into the two variables respectively, how would I go about that? Thanks!
open MYFILE, '<', 'source_file.txt' or die $!;
open OUTFILE, '>', 'Header.txt' or die $!;
$user = 0;
$pass = 0;
while (<MYFILE>) {
chomp;
my #header = split (' ',$_);
print OUTFILE "$linenum: #header\n\n";
if (/USER/ig) {
$user++;
}
if (/PASS/ig) {
$pass++;
}
}
Above is the new code and it works.
I set my variables equal to 0 and used the ++ incrementor on the variables.
But I am still open to suggestions perhaps on expanding my regex's capabilities? (if that makes sense)
You could simply do.
my $user = 0;
my $pass = 0;
while (<MYFILE>) {
chomp;
my #header = split ' ', $_;
print OUTFILE "$linenum: #header\n\n";
$user++ if /user/ig;
$pass++ if /pass/ig;
}
I have created a Perl file to load in an array of "Stop words".
Then I load in a directory with ".ner" files contained in it.
Each file gets opened and each word is split and compared to the words in the stop file.
If the word matches the word it is changed to "" (nothing-and gets removed)
I then copy the file to another location. So I can differentiate between files with stop words and files without.
But does this change the file to now contain no stop words or will it revert back to the original?
#!/usr/bin/perl
#use strict;
#use warnings;
my #stops;
my #file;
use File::Copy;
open( STOPWORD, "/Users/jen/stopWordList.txt" ) or die "Can't Open: $!\n";
#stops = <STOPWORD>;
while (<STOPWORD>) #read each line into $_
{
chomp #stops; # Remove newline from $_
push #stops, $_; # add the line to #triggers
}
close STOPWORD;
$dirtoget="/Users/jen/temp/";
opendir(IMD, $dirtoget) || die("Cannot open directory");
#thefiles= readdir(IMD);
foreach $f (#thefiles){
if ($f =~ m/\.ner$/){
print $f,"\n";
open (FILE, "/Users/jen/temp/$f")or die"Cannot open FILE";
if ( FILE eq "" ) {
close FILE;
}
else{
while (<FILE>) {
foreach $word(split(/\|/)){
foreach $x (#stops) {
if ($x =~ m/\b\Q$word\E\b/) {
$word = '';
copy("/Users/jen/temp/$f","/Users/jen/correct/$f")or die "Copy failed: $!";
close FILE;
}
}
}
}
}
}
}
closedir(IMD);
exit 0;
The format of the file I am splitting and comparing is as follows:
'<title>|NN|O Woman|NNP|O jumped|VBD|O for|IN|O life|NN|O after|IN|O firebomb|NN|O attack|NN|O -|:|O National|NNP|I-ORG News|NNP|I-ORG ,|,|I-ORG Frontpage|NNP|I-ORG -|:|I-ORG Independent.ie</title>|NNP|'
Should I be outlining where the words should be split ie: split(/|/)?
You should ALWAYS use :
use strict;
use warnings;
use three args open and test opening for failure.
As said codaddict A split with no arguments is equivalent to split(' ', $_).
Here is a proposal to achieve the job (as far as I well understood what you wanted).
#!/usr/bin/perl
use strict;
use warnings;
use 5.10.1;
my #stops = qw(put here your stop words);
my %stops = map{$_ => 1} #stops;
my #thefiles;
my $path = '/Users/jen/temp/';
my $out = $path.'outputfile';
open my $fout, '>', $out or die "can't open '$out' for writing : $!";
foreach my $file(#thefiles) {
next unless $file =~ /\.ner$/;
open my $fh, '<', $path.$file or die "can't open '$file' for reading : $!";
my #lines = <$file>;
close $fh;
foreach my $line(#lines) {
my #words = split/\|/,$line;
foreach my $word(#words) {
$word = '' if exists $stops{$word};
}
print $fout join '|',#words;
}
}
close $out;
A split with no arguments is equivalent to split(' ', $_).
Since you want the lines to be split on | you need to do:
split/\|/
#jenniem001,
open FILE, ("<$fh")||die("cant");undef $/;my $whole_file = <FILE>;foreach my $word (#words){$whole_file=~s/\b\Q$word\E\b//ig;}open FILE (">>$duplicate")||die("cant");print FILE $whole_file;
That will remove stops from your file and create a duplicate. Just call give $duplicate a name :)
I am a noob Perl user trying to get my work done ASAP so I can go home on time today :)
Basically I need to print the next line of blank lines in a text file.
The following is what I have so far. It can locate blank lines perfectly fine. Now I just have to print the next line.
open (FOUT, '>>result.txt');
die "File is not available" unless (#ARGV ==1);
open (FIN, $ARGV[0]) or die "Cannot open $ARGV[0]: $!\n";
#rawData=<FIN>;
$count = 0;
foreach $LineVar (#rawData)
{
if($_ = ~/^\s*$/)
{
print "blank line \n";
#I need something HERE!!
}
print "$count \n";
$count++;
}
close (FOUT);
close (FIN);
Thanks a bunch :)
open (FOUT, '>>result.txt');
die "File is not available" unless (#ARGV ==1);
open (FIN, $ARGV[0]) or die "Cannot open $ARGV[0]: $!\n";
$count = 0;
while(<FIN>)
{
if($_ = ~/^\s*$/)
{
print "blank line \n";
count++;
<FIN>;
print $_;
}
print "$count \n";
$count++;
}
close (FOUT);
close (FIN);
not reading the entire file into #rawData saves memory, especially in the case of large files...
<FIN> as a command reads the next line into $_
print ; by itself is a synonym for print $_; (although I went for the more explicit variant this time...
Elaborating on Ron Savage's solution:
foreach $LineVar (#rawData)
{
if ( $lastLineWasBlank )
{
print $LineVar;
$lastLineWasBlank = 0;
}
if($LineVar =~ /^\s*$/)
{
print "blank line \n";
#I need something HERE!!
$lastLineWasBlank = 1;
}
print "$count \n";
$count++;
}
I'd go like this but there's probably other ways to do it:
for ( my $i = 0 ; $i < #rawData ; $i++ ){
if ( $rawData[$i] =~ /^\s*$/ ){
print $rawData[$i + 1] ; ## plus check this is not null
}
}
J.
sh> perl -ne 'if ($b) { print }; if ($b = !/\S/) { ++$c }; END { print $c,"\n" }'
Add input filename(s) to your liking.
Add a variable like $lastLineWasBlank, and set it at the end of each loop.
if ( $lastLineWasBlank )
{
print "blank line\n" . $LineVar;
}
something like that. :-)