Chris Muench
Chris Muench

Reputation: 18338

How to count number of rows in PowerShell

I have a text file that I need to read in PowerShell.

The last character in each row is either a Y or a N.

I need to go through the file and output how many Y's and N's are in there.

Any ideas?

Upvotes: 13

Views: 52970

Answers (6)

Shay Levy
Shay Levy

Reputation: 126912

Get-Content test.txt | Where-Object {$_ -match '[YN]$'} | Group-Object {$_[-1]} -NoElement

Upvotes: 2

mjolinor
mjolinor

Reputation: 68341

$lastchar = @{};get-content $file |% {$lastchar[$_[-1]]++};$lastchar

Upvotes: 1

Doug Finke
Doug Finke

Reputation: 6823

$(foreach ($line in [IO.File]::ReadAllLines(".\test.txt")) { 
    $line.Substring($line.Length - 1)
}) | Group 

Upvotes: 0

stej
stej

Reputation: 29479

I like the answer by @manojlds, so I'll throw something similar:

$grouped = (gc .\test.txt) -replace ".*(y|n)$",'$1' | group

(operators can be used on arrays as well).

Then you can use it like this:

($grouped | ? {$_.Name -eq 'y'}).count

Upvotes: 0

manojlds
manojlds

Reputation: 301527

To get both the counts in a single line:

gc .\test.txt | %{ if($_ -match "Y$|N$"){ $matches[0]} } | group

Upvotes: 7

Aaron
Aaron

Reputation: 57808

Assuming a file named "test.txt"... To get the number of lines ending in Y, you can do this:

get-content test.txt | select-string Y$ | measure-object -line

And to get the number of lines ending in N, you can do this:

get-content test.txt | select-string N$ | measure-object -line

Hope that helps.

Upvotes: 24

Related Questions