jeudi 24 novembre 2016

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

  • 5
  • 5
  • 5
  • 5
  • 2
  • 5
  • 2
  • 5

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?

Aucun commentaire:

Enregistrer un commentaire