Re: grep from one file and write to another Vahid Moghaddasi wrote: > Hi all, Hello, > I am trying to read a colon delimited text file (filter.in) then > search for each field in another file (/etc/passwd) and if it is found > then write that line in the third file (passwd.out). Here is what I > have written so far but it is not given me the correct result. Thanks > for any help. >  >  > #!/bin/perl > # > # the format of filter.in is user1:user2:user3:user4: > # > use File::Copy; > use strict; > use warnings; > $|=1;           # flush output buffer > open (FILTERfh, "< filter.in") || die "Can not open filter.in: $!\\n"; > open PASSWDfh, ' open PASSWDFILfh, ">passwd.out"; > while () { > chomp; > my @input = split /:/, $_; >    for (my $user = 1; $user <= $#input ; $user++) { >        print "$input[$user] is being added.\\n"; >        while () { >                my %seen; >                next if (m/^#/);        # Skip comments >                next if (m/^\\s*$/);     # Skip blank lines >                my ($field1) = /([^:]+)/; > #      print PASSWDFILfh $_ unless $seen{$field1} or warn > #      "WARNING: User $input[$user] does not exist!\\n"; >      print PASSWDFILfh $_ unless $input[$user] or warn >      "WARNING: User $input[$user] does not exist!\\n"; > # print PASSWDFILfh $_ if("$field1" eq "$input[$user]"); > #        print PASSWDFILfh $_ if( grep(/$field1:/, $_ )) or warn > "WARNING: User $input[$user] does not exist!\\n"; >     } # while > } # for > } # while > close FILTERfh; > close PASSWDFILfh; > close PASSWDfh; Something like this should work: #!/bin/perl # # the format of filter.in is user1:user2:user3:user4: # use strict; use warnings; open FILTERfh,    '<', 'filter.in'  or die "Can not open filter.in: $!\\n"; open PASSWDFILfh, '>', 'passwd.out' or die "Can not open passwd.out: $!\\n"; while (  ) {      chomp;      my @input = split /:/;      for ( @input ) {          if ( getpwnam $_ ) {              print PASSWDFILfh $_;              }          else {              warn "WARNING: User $_ does not exist!\\n";              }          }      } close FILTERfh; close PASSWDFILfh; John --  Perl isn't a toolbox, but a small machine shop where you can special-order certain sorts of tools at low cost and in short order.                            -- Larry Wall --  To unsubscribe, e-mail: beginners-unsubscribe@perl.org For additional commands, e-mail: beginners-help@perl.org http://learn.perl.org/