2017-09-13 75 views
1

好吧,Powershell可能不是該作業的最佳工具,但它是唯一可用的工具。無法將字符數組寫入Powershell中的文件

我有一堆600K +行.csv數據文件。其中一些具有分隔符錯誤,例如「在一個文本字段中,或者在一個字符開始處」「,它們太大而無法編輯(即使是在UltraEdit中),並且手動修復,即使我想要我不想修改它也不會!

因爲double- 「」 - 在一些文本字段和流氓開頭的三角 - 「 - 在一些文本字段中間的分隔符,我沒有使用標題行來定義列,因爲這些行看起來好像有一個額外的列在他們由於額外的分隔符。

我需要解析文件尋找「」,而不是「在文本字段的開始,並在文本字段的中間尋找」並刪除它們。

我已經設法通過將整個文件讀入一個數組,並將輸出字符添加到輸出數組中來完成此操作(在時尚之後)。

我沒有設法做的是成功地寫這個輸出數組到一個文件。

我已閱讀看似相關的https://docs.microsoft.com/en-us/powershell/module/Microsoft.PowerShell.Utility/out-file?view=powershell-5.1的每一部分。我還瀏覽了本網站上的大約10個類似問題,並試圖從他們那裏收集各種代碼。

輸出數組使用寫主機完美地打印到屏幕上,但我無法將數據返回到愛或金錢的文件中。到目前爲止,我總共有1.5天的Powershell體驗!所有建議感激地收到。

這裏是我的代碼來讀取/識別惡意分隔符(不漂亮(全部),是指數據和現有技術的限制的前面的解釋):

$ContentToCheck=get-content 'myfile.csv' | foreach { $_.ToCharArray()} 
[email protected]() 

for ($i = 0; $i -lt $ContentToCheck.count; $i++) 
{ 
    if (!($ContentToCheck[$i] -match '"')) {#not a quote 

    if (!($ContentToCheck[$i] -match ',')) {#not a comma i.e. other char that could be enclosed in "" 


     if ($ContentToCheck[$i-1] -match '"') {#check not rogue " delimiter in previous char allow for start of file exception i>1? 


      if (!($ContentToCheck[$i-2] -match ',') -and !($ContentToCheck[$i-3] -match '"')){ 
       Write-Host 'Delimiter error' $i 
       $ContentOutputArray+= '' 

      }#endif not preceded by ", 


     }#endif" 

     else{#previous char not a " so move on 

      $ContentOutputArray+= $ContentToCheck[$i] 

     } 

    }#endifnotacomma 

    else 
    {#a comma, include it 

     $ContentOutputArray+= $ContentToCheck[$i]  
    }#endacomma 

}#endifnotaquote 

else 
{#a quote so just append it to the output array 

    $ContentOutputArray+= $ContentToCheck[$i] 

}#endaquote 

}#endfor 

到目前爲止好,如果不雅觀。如果我做一個簡單

Write-Host $ContentOutputArray 

數據顯示很好 「6 5」, 「652 | | 999」, 「99」, 「」, 「678 | | 1」 .....此外當我檢查(基於問題文件之一的縮減版本)

$ContentOutputArray.count 

我得到2507字符長度的數組。快樂。然而,然後使用不同:

$ContentOutputArray | Set-Content 'myfile_FIXED.csv' 

創建空白文件

$ContentOutputArray | out-file 'myfile_FIXED.csv' -encoding ASCII 

創建空白文件

$ContentOutputArray | export-csv 'myfile_FIXED.csv' 

只給出了「#TYPE系統。字符」文件

$ContentOutputArray | Export-Csv 'myfile_FIXED.csv' -NoType 

給空文件

$ContentOutputArray >> 'myfile_FIXED.csv' 

給人以空格隔開,

還有什麼我可以嘗試寫字符數組到一個平面文件?這似乎是一個基本的問題,但它讓我難堪。謝謝閱讀。

+1

您正在使用哪個版本的powershell? –

+0

Version 2.0 Matthias – Hilary

回答

4

將char數組轉換(或轉換)爲字符串,然後再導出它。

(New-Object string (,$ContentOutputArray)) |Set-Content myfile_FIXED.csv 
+0

嗨,拋出一個錯誤,所以我修改它爲[字符串] $ ContentOutputArray | Set-Content'myfile_FIXED.csv',它的工作魅力。非常感謝。 – Hilary