texuser74 has asked for the wisdom of the Perl Monks concerning the following question:

I want to extract only those lines that start with "@" character from a input text file.

when i tried the following code, only 1 line is getting extrated(first instance). But there are more than 1 line in input text file that starts with "@".

open(IN, "<input.txt"); while(<IN>) { s#\@(.*?)\n##;my $temp=$1; print "output: $temp\n"; } close(IN);

Please advise.

20040907 Edit by ysth: code in code tags

Replies are listed 'Best First'.
Re: working with files
by davorg (Chancellor) on Sep 03, 2004 at 10:46 UTC
    open(IN, 'input.txt') or die $!; print map { "output: $_" } grep { /^@/ } <IN>;
    --
    <http://www.dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: working with files
by Arunbear (Prior) on Sep 03, 2004 at 10:45 UTC
    open(IN, "<input.txt") or die $!; while(<IN>) { chomp; next unless /^@(+.)/; print "output: $1\n"; } close(IN);
Re: working with files
by bronto (Priest) on Sep 03, 2004 at 10:54 UTC
    perl -ne 'print "output: $_" if /^\@/' filename

    Ciao!
    --bronto


    The very nature of Perl to be like natural language--inconsistant and full of dwim and special cases--makes it impossible to know it all without simply memorizing the documentation (which is not complete or totally correct anyway).
    --John M. Dlugosz
Re: working with files
by tachyon (Chancellor) on Sep 03, 2004 at 10:57 UTC
    perl -ne '/^@/ && print' infile > outfile

    Use " insead of ' on Win32

    cheers

    tachyon

Re: working with files
by THuG (Beadle) on Sep 03, 2004 at 12:52 UTC

    There are lots of good solutions here, but no answers as to why your code isn't working.

    I suspect it is because of the minimal approach (dot star question) instead of the maximal (dot star) and the attempt to include the newline.

    I think the answer that includes chomp and the match-at-beginning-of-string caret should work with littlest change to your code, so you can check out the differences. There are slimmer solutions, though.

      Thanks for all your help.
Re: working with files
by rupesh (Hermit) on Sep 03, 2004 at 10:43 UTC
    Untested...
    use strict; open FH, '<', 'filename'; foreach (<FH>) { print $_ if /^\@/; } close FH;
Re: working with files
by Anonymous Monk on Sep 03, 2004 at 11:46 UTC
    sed -n /^@/s///p input.txt grep ^@ input.txt | cut -c 2- awk '/^@/{sub ("@",""); print}' input.txt perl -ane 'length shift' -e@F -F@ -e' or print @F' input.txt