Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

print if // line number?

by ZWcarp (Beadle)
on Jun 07, 2011 at 22:38 UTC ( #908588=perlquestion: print w/ replies, xml ) Need Help??
ZWcarp has asked for the wisdom of the Perl Monks concerning the following question:

I am wondering how to write the awk one liner :

cat <filename> | awk '$2 ~ /GRHL3/{print NR"\t"$0}'

which prints out the( or any) line that has the string "GRHL3" in it as well as its respective line number

the perl one liner for the same task I have so far is perl -ne 'print if /GRHL3/' <filename>

What do I have to add so that it will also print out the line number ... I feel like $. has to go somewhere? Thanks so much!! Also does someone know of a good web resource where you can look this sort of thing up (specifically about one liners).

Comment on print if // line number?
Select or Download Code
Replies are listed 'Best First'.
Re: print if // line number?
by ikegami (Pope) on Jun 07, 2011 at 23:08 UTC

    What you said it does, in case that's what you want:

    perl -ne'print "$.\t$_" if /GRHL3/'

    What it actually does (only the second field is checked for the pattern):

    perl -ane'print "$.\t$_" if $F[1] =~ /GRHL3/'

    $. is in perlvar, and -n and -a are in perlrun.

      Shoot you're right sorry...yeah I meant with out the $2 (specifying the field) ...just across the whole line

Re: print if // line number?
by kennethk (Abbot) on Jun 07, 2011 at 22:43 UTC
    awk's NR maps to Perl's $., so you should get your expected result with something like perl -ne 'print "$.:\t$_" if /GRHL3/' <filename>.

    My experience has been that the best general reference when you are trying to track down 'magic' behavior is usually perlvar.

Re: print if // line number?
by toolic (Bishop) on Jun 07, 2011 at 22:46 UTC
    Also does someone know of a good web resource where you can look this sort of thing up (specifically about one liners).
    One Liners

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://908588]
Approved by kennethk
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others about the Monastery: (8)
As of 2015-07-31 02:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (274 votes), past polls