Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid

A new question from the front line

by bronto (Priest)
on Oct 18, 2002 at 07:47 UTC ( #206239=perlquestion: print w/replies, xml ) Need Help??
bronto has asked for the wisdom of the Perl Monks concerning the following question:

Hello fellow monks

Do you remember the question Save all but line 32!? Yesterday I had another question to which I gave a reply but I am interested again in how you had resolved the same issue. Here we go:

A colleague of mine asked me: "I have a text file that contains data record as lines; here and there between the data you have rows that tell you the names of the columns. If I find a line that contains, say, the word energy I want to print the line that follows it. In similar cases I resolved with awk, but I can't get a solution for this one and I don't want to code it in FORTRAN".

My solution was:

perl -ne 'print scalar <> if /energy/' filename

He then asked me if I could add a counter, and I slightly modified the previous in:

perl -ne 'print ++$i,scalar <> if /energy/' filename

What's your solution for this?


# Another Perl edition of a song:
# The End, by The Beatles
  $you->take($love) eq $you->make($love) ;

Replies are listed 'Best First'.
Re: A new question from the front line
by jmcnamara (Monsignor) on Oct 18, 2002 at 08:31 UTC

    Here's another way:
    perl -ne 'print if $prev; $prev = /energy/' file # Or with a counter perl -ne 'print ++$i, $_ if $prev; $prev = /energy/' file
    Your second solution could have been written as follows:     perl -ne 'print ++$i . <> if /energy/' filename


Re: A new question from the front line
by blakem (Monsignor) on Oct 18, 2002 at 08:15 UTC
    If you know 'energy' wont occur on successive lines, how about:
    perl -pe'$_=/\benergy\b/&&<>'


      His own code doesn't fulfill the successive lines criterion either. Golf time: perl -pe'$_=/energy/?<>:""'
      Hmm, yours beats me if you take out the \b though.

      Makeshifts last the longest.

Re: A new question from the front line
by Chmrr (Vicar) on Oct 18, 2002 at 11:44 UTC

    I'd probably do it more or less the same way you did; but for perversity's sake, here's another possibility:

    perl -ple 'BEGIN{$/="energy";<>;$.--}/.+/;$_=$..$&' filename

    perl -pe '"I lo*`+$^X$\"$]!$/"=~m%(.*)%s;$_=$1;y^`+*^e v^#$&V"+@( NO CARRIER'

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://206239]
Approved by fireartist
[choroba]: my son #2 would eat them all, regardless of the design :-)

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (11)
As of 2017-12-16 16:11 GMT
Find Nodes?
    Voting Booth?
    What programming language do you hate the most?

    Results (456 votes). Check out past polls.