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 (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 `;
    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