【问题标题】:powershell - rename csv file based on a column valuepowershell - 根据列值重命名csv文件
【发布时间】:2013-10-25 01:13:34
【问题描述】:

我的 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 列的行(文件名应包含第 3 列)和不包含第 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 

我参考了 stackoverflow 问题 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
}

【问题讨论】:

    标签: powershell csv rename


    【解决方案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

    如果你想创建没有标题行的输出文件,你需要替换

    ... | Export-Csv $outfile -NoTypeInformation
    

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

    【讨论】:

    • 抱歉,我不清楚。我在我的问题中添加了一个示例输出。文件中的其他行必须写入另一个文件。所以,必须有这些文件:(1)。没有第 3 列 (2) 的文件。具有第 3 列的文件,但是,第 3 列要附加到文件名。希望这很清楚。
    • @Sarvavyapi 是的,谢谢你的澄清。基本上你需要结合我之前的建议。查看更新的答案。
    • 谢谢。这很好用。但是输出中有“”。我尝试像这样删除它: $csv | ? { $null, '' -notcontains $_.Address } |转换为-csv -NoTypeInformation | %{$_ -replace '"', ""} | 组对象地址 | % { $n++ $outfile = "File_${n}-" + $_.Name.Replace(':', '') + '.txt' $_.Group | out-file $outfile -fo -en ascii #Export-Csv $outfile -NoTypeInformation }
    • 我想通了。 $csv | ? { $null, '' -notcontains $_.Address } |组对象地址 | % { $n++ $outfile = "File_${n}-" + $_.Name.Replace(':', '') + '.txt' $_.Group |转换为-csv -NoTypeInformation | %{$_ -replace '"', ""} | 输出文件 $outfile -fo -en ascii }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-11
    • 2019-05-14
    • 2020-01-05
    相关资源
    最近更新 更多