13

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?

6 Answers 6

24

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.

Sign up to request clarification or add additional context in comments.

1 Comment

for any googlers that want this answer in a variable here it is [code] $a = (Get-Content filename.txt| Select-String "|Y $" | Measure-Object).count [/code]
7

To get both the counts in a single line:

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

Comments

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

Comments

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

Comments

0

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.