netz
netz

Reputation: 21

Powershell if foreach(

I have to find in a quite large file all lines which content more then 4 ;

For example this file

Text1;Text2;Text3;Text4;Text5;
Text1;Text2;Text3;Text4;Text5;
Text1;Text2;Text3;Text4;Text5;
Text1;Text2;Text3;Text4;Text5;
Text1;Text2;Text3
Text1;Text2;Text3;Text4;Text5;
Text1;Text2;Text3
Text1;Text2;Text3;Text4;Text5;

Counting the lines is no problem

$content=Get-Content .\sample.txt
[regex]::matches($content,";").count

gives me 34 hits.

Counting the desired chars per line also no problem

$content=Get-Content .\sample.txt
foreach ($lines in $content) {[regex]::matches($lines,";").count}

Gives

Now I would like to get all lines where I have less then 4 ;

I tried this:

if (foreach ($lines in $content) {[regex]::matches($lines,";").count} -le 3) {Write-Host $lines}

But this gives me an error.

With this

$count=foreach ($lines in $content) {[regex]::matches($lines,";").count}
if ($count -le 3) {Write-Host $lines}

I get one line - the final matching line, but not the other.

How to combine foreach and if?

Upvotes: 2

Views: 1821

Answers (3)

TessellatingHeckler
TessellatingHeckler

Reputation: 29033

PS D:\test> (sls -n '(.*;){4}' sample.txt).line
Text1;Text2;Text3
Text1;Text2;Text3

# or in long form:
PS D:\test> Select-String -NotMatch -Pattern '(.*;){4}' -Path .\sample.txt | Select-Object -ExpandProperty Line

The regex matches at least 4 semicolons with anything between them. -NotMatch gets the lines that don't match that regex - i.e. less than 4 semicolons.

Upvotes: 0

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174690

A more PowerShell-idiomatic way to solve this would be to use the Where-Object filter cmdlet:

$Lines = Get-Content .\sample.txt |Where-Object { [regex]::Matches($_,';').Count -le 3 }

Upvotes: 2

Christos Lytras
Christos Lytras

Reputation: 37318

Your syntax is wrong with this code:

if (foreach ($lines in $content) {[regex]::matches($lines,";").count} -le 3) {Write-Host $lines}

You dont put foreach inside an if statement's condition parenthesis. Use the if statement inside the foreach instead like this:

$content=Get-Content .\sample.txt
foreach ($lines in $content) {
    $semiCols = [regex]::matches($lines,";").count
    if($semiCols -le 3) {
        Write-Host $semiCols
    }
}

OUTPUT

PS E:\Programming\PowerShell> .\lines-fetch.ps1
2
2
PS E:\Programming\PowerShell>

Upvotes: 1

Related Questions