2016-08-01 39 views
0

我想通过以下查询循环并拆分当前目录中的所有文本文件。我目前有两个不同的文件,分别命名为TestingInfo[1] & TestingInfo[2]循环为txt拆分文件

目录文件所在的位置:\\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

我在这里看到几件事。你不能很好地解释你希望完成什么。你想要3个输出文件吗?你期望他们包含什么?他们应该命名什么?另外,''[IMPORT]“'对于'-match'参数不是一个好的正则表达式匹配。这将匹配任何包含至少一个字符I,M,P,O,R或T的行([请参阅此处的示例](https://regex101.com/r/kV3wZ7/1)) – TheMadTechnician

+0

例如,如果Select-String -Between'IMPORT'在一次移动中选择所有导入组,则整洁(如果存在)。为它投票,如果你也认为它会很整洁:https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/14951235-add-parameters-to-select-string-for-matching-all-l – TessellatingHeckler

+0

我试图解释的是,我有两个文件包含上面发布的txt。第一个文件TestingInfo [1]有两组记录,我需要将这两组记录提取到单独的文件中,第二个文件测试TestingInfo [2]有一个。无论文件夹中有多少个文件,我都希望这个功能能够将每个文件块分开。它们的名称并不重要。就像“TestingInfo [1] _N”,其中N将等于来自该文件的块的数量。 –

回答

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

其中给出的文本文件,其中的内容是这样的:

重用你的代码,并在获取子项将会是什么样子:

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

在您的代码中,我看到它重复testsInfo [1]文件两次。我需要将两个文件中的所有数据块分散到不同的文件中。在我的代码中,我能够做到这一点,但我不能遍历目录中的所有文件并执行相同的操作。因此原始的“TestingInfo1”文件将被分成两个单独的文件:结果文件1:[IMPORT] 1 2 3结果文件2:[IMPORT] 4 5 6 –

+0

原始文件“TestingInfo [2]”。生成的文件将是结果文件1:[IMPORT] 7 8 9 10 –

+0

啊,这很简单。只需将其全部包装在get-childitem中,并用$ _或$ _替换文件名。FullName(编辑上述内容) –