Reputation: 76
php -R '$count++' -E 'print "$count\n";' < somefile
will print the number of lines in 'somefile' (not that I would actually do this).
I'm looking to emulate the -E switch in a perl command.
perl -ne '$count++' -???? 'print "$count\n"' somefile
Is it possible?
Upvotes: 2
Views: 227
Reputation: 67900
TIMTOWTDI
You can use the Eskimo Kiss operator:
perl -nwE '}{ say $.' somefile
This operator is less magical than one thinks, as seen if we deparse the one-liner:
$ perl -MO=Deparse -nwE '}{say $.' somefile
BEGIN { $^W = 1; }
BEGIN {
$^H{'feature_unicode'} = q(1);
$^H{'feature_say'} = q(1);
$^H{'feature_state'} = q(1);
$^H{'feature_switch'} = q(1);
}
LINE: while (defined($_ = <ARGV>)) {
();
}
{
say $.;
}
-e syntax OK
It simply tacks on an extra set of curly braces, making the following code wind up outside the implicit while loop.
Or you can check for end of file.
perl -nwE 'eof and say $.' somefile
With multiple files, you get a cumulative sum printed for each of them.
perl -nwE 'eof and say $.' somefile somefile somefile
10
20
30
You can close the file handle to get a non-cumulative count:
perl -nwE 'if (eof) { say $.; close ARGV }' somefile somefile somefile
10
10
10
Upvotes: 10
Reputation: 50858
You can use an END { ... }
block to add code that should be executed after the loop:
perl -ne '$count++; END { print "$count\n"; }' somefile
You can also easily put it in its own -e
argument, if you want it more separated:
perl -ne '$count++;' -e 'END { print "$count\n"; }' somefile
See also:
Upvotes: 6
Reputation: 2791
This should be what you're looking for:
perl -nle 'END { print $. }' notes.txt
Upvotes: 6