in reply to Read and parse text file

#!perl open (FILEH, "/etc/passwd"); #open the file for read while (<FILEH>) { #while there are still lines in FILEH... chomp; #clear newlines... if ( /root/i ) { # if line contains "root" case insensitive` ($username,$id) = (split /:/)[0,2]; #pull out field one and th +ree print "User: $username, ID: $id\n"; #print junk } }
this is similar to the unix commands:
grep -i root /etc/passwd | awk '{ ... You can figure it out.


-Waswas

Replies are listed 'Best First'.
Re: Re: Read and parse text file
by RCP (Acolyte) on Feb 24, 2004 at 12:40 UTC
    Thanks for the short code, it's exaclly what I was looking for. My unix scripts finds specific files generated by a software's report, extracts specific data from columns and writes out a "macros" to execute within the software. I was supposed to start PERL class next week, but heart surgery cut that short, now I have something to do while I'm at home recuperating. Thanks! RCP
Re: Re: Read and parse text file
by RCP (Acolyte) on Mar 08, 2004 at 18:23 UTC
    #!perl open (FILEH, "/etc/passwd"); #open the file for read while (<FILEH>) { #while there are still lines in FILEH... chomp; #clear newlines... if ( /root/i ) { # if line contains "root" case insensitive` ($username,$id) = (split /:/)[0,2]; #pull out field one and th +ree print "User: $username, ID: $id\n"; #print junk } }
    Thanks again for your help earlier. I was wondering if there was a way to have this script read each line in a file and if there is not a fourth column, do not write that line out. If there is a fourth column, then write the line out. Thanks, RCP
      If you're splitting on ':',
      while (<>) { print if tr/:// >= 3; # Special use of tr to count column separato +rs }
      To count columns more literally, and splitting on the more traditional whitespace:
      while (<>) { my @cols = split; print if @cols >= 4; }

      The PerlMonk tr/// Advocate
        Your second approach worked much better! Thanks again... RCP