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

Can anyone show me how to write a script to count the number of lines starting with a "+" sign. It should be starting with a plus and followed by a space.

Replies are listed 'Best First'.
Re: count number of lines with +
by vinoth.ree (Monsignor) on Jul 22, 2014 at 10:08 UTC

    Gets input from user (i.e, from STDIN)

    my @array = grep { /^\+\s+/, print $_ } <> ; print scalar @array;

    If you pass the file name as command line argument also this script works, <> will check for @ARGV array for input file.So if you call this script as perl pattenmatch.pl filename.txtwhatever is in @ARGV is used instead.


    All is well
      thanks for the reply. the script printed all the lines with and without + at start. i just want to count the number of lines starting with a + and also i need to ignore ones dont have any other characters. ex :- + abc +bc + output should be - 2 lines.

        Could you please share your sample input data, I will check with my script and let you know.


        All is well
Re: count number of lines with +
by Anonymous Monk on Jul 22, 2014 at 09:39 UTC
    perl -lne '$i++ if /^+ /}{print $i' FILENAME
      thank you for the reply. but i could not got this to work.
        String found where operator expected at 2.pl line 2, near "lne '$i++ if /^+ /}{print $i'" (Do you need to predeclare lne?) Number found where operator expected at 2.pl line 2, near "'$i++ if /^+ /}{print $i' 1" (Missing operator before 1?) syntax error at 2.pl line 2, near "lne '$i++ if /^+ /}{print $i'" Execution of 2.pl aborted due to compilation errors.

        It's not a script meant to be saved to a file - it's a "one-liner", meaning a command that you enter on the command line (aka in your shell). That's the same place you would normally enter, for example, perl scriptfilename.pl

Re: count number of lines with +
by locked_user sundialsvc4 (Abbot) on Jul 22, 2014 at 15:24 UTC

    Also don’t overlook the possibility of using a command-line utility.   For example, the egrep -c regex_pattern utility is available in Unix/Linux land, and comparable facilities are finally also available in Windows PowerShell.

    Use care in building your regex.   For example, do you or do you not want to count lines which contain only a plus-sign in the first position, i.e. followed directly by end-of-line rather than a space?   It will be a really good idea to construct a very short test-file, four or five lines long, which will thoroughly exercise all of the possibilities that you are (and are not ...) looking for, and whose right-answers are known in advance.   Carefully consider every “edge case,” and include them in your test-data file.   “Trust, but Verify.”   Write the command-line (or the Perl), then prove that it works.