txt拆分文件的循环

时间:2016-08-01 22:28:21

标签: powershell

我正在尝试进行以下查询循环并拆分当前目录中的所有文本文件。我目前有两个名为TestingInfo[1]&的文件。 TestingInfo[2]

文件所在的目录:\\C\users$\Pepe\Desktop\TestInfoFolder

文件如下所示:

TestingInfo[1]

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

TestingInfo[2]

[IMPORT]
7
8
9
10

我到目前为止的代码:

$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
}

1 个答案:

答案 0 :(得分:0)

你这样做很难,直接调用.NET库。

这种方法应该是正确的,并且更简单/与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"
  }
}

提供内容如下的文本文件:

  

1 2 3

重用您的代码,并添加get-child项目如下所示:

$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
   }
}