On Thu, 20 Nov 2008 06:32:51 -0800 (PST)
marys <[EMAIL PROTECTED]> wrote:
> Hello:
> Does anyone know how to use ‘awk’ in a script? It must have a
> different syntax than the unix analog, as does the ‘grep’ command.
> For grep, the syntax in the c-shell is:
> “grep ‘string’ , but for Perl the delimiters are slashes: $x = grep /
> string/ line.
> Maybe the same thing is going on with Perl.
>
> I have searched the following sources with no help on awk:
>
> perldoc -f ‘awk’
> ‘Beginning Perl’ by S. Cozen
> ‘CGI101’
> and the O’Reilly books:
> ‘Learning Perl’ aka the llama book
> ‘Intemediate Perl’
> ‘Advanced Perl’
> ‘CGI Programming with Perl’
>
> I have a file called /tmp/file.txt with one line:
>
> field xxxx
>
> for grepping on xxxx, the script is:
>
>
> #!/usr/bin/perl -w
> use CGI::Carp qw(fatalsToBrowser);
> use CGI qw(:standard -no_xhtml);
> #use CGI ':standard';
> use strict;
> use diagnostics;
> my $q = new CGI;
> print $q->header;
> print $q->start_html(-title=>"mygrep");
>
>
> my @infile;
> my $q = new CGI;
> open (FILEIN, "/tmp/file.txt") or die "Can't open /tmp/file.txt for
> reading: $!\n!";
> open (FILEOUT, ">/tmp/out.txt") or die "Can't open /tmp/out.txt for
> writing: $!\n!";
> system "chmod 755 /tmp/out.txt";
>
>
> while ( defined(my $line=<FILEIN>) ){
> chomp($line);
> push (@infile,$line);
> }
>
> my @zoom = grep(/xxxx/,@infile); #looks for 'xxxx' in @infile
>
> foreach (@zoom){
> print $q->center($q->h3("\nNext line containing 'xxxx' is:
> \n"),
> $q->h3("$_\n"),
> $q->h3("_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _") );
> }
>
> print $q->center($q->h2(" grep program is finished!\n"));
>
> _______________________________________________________________________
>
>
>
> The script works as it should for grep, but what if I want to output
> $NF (=xxxx) when a line has the string ‘field’ in it? There must be
> a way, but I can't find it.
I am not altogether certain what you are trying to achieve.
Read up on $. (See perldoc perlvar) That gives you the line number
that you are reading.
Also I think you night be better off using a regex.
if ($line =~ /xxxx/}{print "$. $line\n"};
This gives you the opportunity to get matches as well as pre and post
matches
If you want to do awk type things, have a read of perldoc English
Owen
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/