Reputation: 18338
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
Reputation: 126912
Get-Content test.txt | Where-Object {$_ -match '[YN]$'} | Group-Object {$_[-1]} -NoElement
Upvotes: 2
Reputation: 68341
$lastchar = @{};get-content $file |% {$lastchar[$_[-1]]++};$lastchar
Upvotes: 1
Reputation: 6823
$(foreach ($line in [IO.File]::ReadAllLines(".\test.txt")) {
$line.Substring($line.Length - 1)
}) | Group
Upvotes: 0
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
Reputation: 301527
To get both the counts in a single line:
gc .\test.txt | %{ if($_ -match "Y$|N$"){ $matches[0]} } | group
Upvotes: 7
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