2013-10-16 44 views
1

我的CSV文件中有這樣的內容:PowerShell的 - 基於列的值重命名CSV文件

currentTime, SeqNum, Address 
1381868225469, 0, 
1381868226491, 1, 38:1c:4a:0:8d:d 
1381868227493, 1, 
1381868228513, 2, 38:1c:4a:0:8d:d 
1381868312825, 43, 
1381868312916, 1694564736, 3a:1c:4a:1:a1:98 
1381868312920, 1694564736, 3a:1c:4a:1:a1:98 
1381868312921, 44, 

根據第3列是否爲空,我希望將文件分成2個或多個文件(那些與含有第三列線(文件名應包含第三列)和一個沒有第3列

實施例輸出:

**File0.txt** 
1381868225469, 0, 
1381868227493, 1, 
1381868312825, 43, 
1381868312921, 44, 

**File1-381c4a08dd.txt** 
1381868226491, 1, 38:1c:4a:0:8d:d 
1381868228513, 2, 38:1c:4a:0:8d:d 

**File2-3a1c4a1a198.txt** 
1381868312916, 1694564736, 3a:1c:4a:1:a1:98 
1381868312920, 1694564736, 3a:1c:4a:1:a1:98 

我所提到的計算器疑問句t HEREHERE以完成我的大部分工作。但是,我想基於第三列重命名我的文件。由於Windows不接受文件名中的「:」,我想在將第三列附加到我的文件名前刪除「:」。我想我的文件名看起來像這樣:

文件名,381c4a08dd.txt

我怎麼去呢?這是我在它的企圖到目前爲止:

import-csv File.txt | group-object Address | foreach-object { 
$_.group | select-object currentTime, SeqNum, Address | convertto-csv -NoTypeInformation | %{$_ -replace '"', ""} | out-file File-$($_.Address.remove(':')).txt -fo -en ascii 
} 

回答

1

嘗試這樣:

$csv = Import-Csv 'C:\path\to\file.txt' 
$n = 0 

# export rows w/o address 
$outfile = 'File${n}.txt' 
$csv | ? { $null, '' -contains $_.Address } | 
    Export-Csv $outfile -NoTypeInformation 

# export rows w/ address 
$csv | ? { $null, '' -notcontains $_.Address } | Group-Object Address | % { 
    $n++ 
    $outfile = "File${n}-" + $_.Name.Replace(':', '') + '.txt' 
    $_.Group | Export-Csv $outfile -NoTypeInformation 
} 

過濾$null, '' -contains $_.Address是必需的,因爲地址的記錄都會被$null,當你有一個空的地址,並沒有尾隨輸入文件最後一行的換行符。

如果不想標題行要創建的輸出文件,你需要用

... | ConvertTo-Csv -NoTypeInformation | select -Skip 1 | Out-File $outfile 
+0

更換

... | Export-Csv $outfile -NoTypeInformation 

我很抱歉,我並不清楚。我已經爲我的問題添加了一個示例輸出。文件中的其他行必須寫入另一個文件。所以,必須有這些文件:(1)。沒有第三欄的文件(2)。第三列的文件,但是,第三列要附加到文件名。希望這是明確的。 – Sarvavyapi

+0

@Sarvavyapi是的,謝謝你澄清。基本上你需要結合我之前的建議。查看更新的答案。 –

+0

謝謝。這很好。但輸出中有「」。我試圖像這樣刪除它:$ csv | ? {$ null,''-notcontains $ _。Address} | convertto-csv -NoTypeInformation | %{$ _ -replace'「',」「} | Group-Object Address |%{ $ n ++ $ outfile =」File _ $ {n} - 「+ $ _。Name.Replace(':','' )+'.txt' $ _。Group | out-file $ outfile -fo -en ascii #Export-Csv $ outfile -NoTypeInformation } – Sarvavyapi