2016-08-01 81 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(編輯上述內容) –