Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask

Re: String searching in file

by poj (Abbot)
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

Replies are listed 'Best First'.
Re^2: String searching in file
by cbtshare (Monk) 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 (Monk) 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 `;

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1208862]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (2)
As of 2020-10-28 18:12 GMT
Find Nodes?
    Voting Booth?
    My favourite web site is:

    Results (263 votes). Check out past polls.