How to count the number of lines in powershell

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

the last character in each line is either Y or N.

I need to go through the file and print how many Y and N are there.

Any ideas?

+5
source share
6 answers

Assuming a file called "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 this helps.

+7
source

To get both accounts on the same line:

gc .\test.txt | %{ if($_ -match "Y$|N$"){ $matches[0]} } | group
+6
source
Get-Content test.txt | Where-Object {$_ -match '[YN]$'} | Group-Object {$_[-1]} -NoElement
+2
$lastchar = @{};get-content $file |% {$lastchar[$_[-1]]++};$lastchar
+1

@manojlds, :

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

( ).

Then you can use it as follows:

($grouped | ? {$_.Name -eq 'y'}).count
0
source
$(foreach ($line in [IO.File]::ReadAllLines(".\test.txt")) { 
    $line.Substring($line.Length - 1)
}) | Group 
0
source

All Articles