Pepe_Fuego Pepe_Fuego - 4 months ago 23
Powershell Question

loop for txt split file

I am trying to make this following query loop through and split all the text files in the current directory. I currently have two different files named

TestingInfo[1]
&
TestingInfo[2]
.

Directory where files are located:
\\C\users$\Pepe\Desktop\TestInfoFolder


The files look like this:

TestingInfo[1]
:

[IMPORT]
1
2
3
[IMPORT]
4
5
6


TestingInfo[2]
:

[IMPORT]
7
8
9
10


Code I have so far:

$Path = "\\C\users$\Pepe\Desktop\TestInfoFolder"
$InputFile = (Join-Path $Path "TestingInfo[1].txt")
$Reader = New-Object System.IO.StreamReader($InputFile)
$N = 1

While (($Line = $Reader.ReadLine()) -ne $null) {
if ($Line -match "[IMPORT]") {
$OutputFile = $matches[0] + $N + ".txt"
$N++
}

Add-Content (Join-Path $Path $OutputFile) $Line
}

Answer

Your sort of doing it the hard way, calling the .NET libraries directly.

This approach should be about right, and much more simple / in line with PowerShell.

$curFileContents
$i = 0

Get-ChildItem "pathOfFiles\" | {
  Get-Content $_ | ForEach-Object {
      $line = $_.Split(" ")
      foreach ($word in $line)
      {
          if ($word -match "[INPUT]")
          {
              $i++
          }
          else
          {
              $curFileContents += $word  + " "
          }
      }
      $curFileContents | Out-File -FilePath "PathToFile\output$i.txt"
  }
}

Which gives text files where the content looks like:

1 2 3

Reusing your code, and adding in the get-child item would look like:

$Path = "\\C\users$\Pepe\Desktop\TestInfoFolder"
Get-ChildItem $Path | foreach-object {
   $InputFile = $_.FullName
   $Reader = New-Object System.IO.StreamReader($InputFile)
   $N = 1

   While (($Line = $Reader.ReadLine()) -ne $null) {
       if ($Line -match "[IMPORT]") {
           $OutputFile = $matches[0] + $N + ".txt"
           $N++
       }

       Add-Content (Join-Path $Path $OutputFile) $Line
   }
}