Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: String searching in file

by poj (Monsignor)
on Feb 09, 2018 at 20:34 UTC ( #1208862=note: print w/replies, xml ) Need Help??


in reply to String searching in file

if (grep /$line/, $awsLists )

Using perl, grep on the lines in the file not the filename. For example (using test data instead of your command output)

#!/usr/bin/perl use warnings; use strict; my $awsLists = '/ansible/awsLists'; my @awsLists = (); if (-e $awsLists){ open my $fh,'<',$awsLists or die "$!"; @awsLists = <$fh>; close $fh; } my $cmd = 'aws ec2 describe-instances --filters "Name=instance-state-n +ame,Values=running" | grep PrivateDnsNam$'; my @output = <DATA>;#qx/$cmd/; open my $fh,'>>',$awsLists or die "$!"; foreach my $line (@output){ chomp($line); if (grep /$line/, @awsLists ){ print "$line found\n"; } else { print "$line not found - added\n"; print $fh $line."\n"; } } close $fh; __DATA__ test 1 test 89
poj

Replies are listed 'Best First'.
Re^2: String searching in file
by cbtshare (Scribe) on Feb 09, 2018 at 22:06 UTC
    Thank you very much, I see what you have done, checking if the file exists, opening it for reading, then opening it again for writing.I was kinda trying to avoid that, and just skip those extra steps and search if it ip address is in the file to begin with, if not write to it. Is there no way to do that, without opening the file for reading and writing?
Re^2: String searching in file
by cbtshare (Scribe) on Feb 09, 2018 at 23:02 UTC
    Sorry but looking at your code more closely, I dont see how it will work, sorry if I didnt put all the details. $awsLists isn't populated, so my goal is to populate the file, then check if ip is there, and not do anything, but if it is there write to the file
    @command=`aws ec2 describe-instances --filters "Name=instance-state-na +me,Values=running" | grep PrivateDnsName | cut -d ":" -f2| cut -d '" +' -f2 | sort -u `;
    Result
    ip-10-1-68-84.us-west-2.compute.internal ip-10-1-7-183.us-west-2.compute.internal ip-10-1-80-15.us-west-2.compute.internal ip-10-1-80-162.us-west-2.compute.internal ip-10-1-80-184.us-west-2.compute.internal ip-10-1-80-187.us-west-2.compute.internal ip-10-1-80-18.us-west-2.compute.internal ip-10-1-80-57.us-west-2.compute.internal

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1208862]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (10)
As of 2018-06-19 07:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?



    Results (111 votes). Check out past polls.

    Notices?