本文介绍了PowerShell将CSV列值拆分为两个独立的列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包含5条记录的CSV文件(实际上约为80,000条)。

CSV文件:

column1,columnICareAbout,column2
someRandomValue,John Doe - Generic,someRandomValue
someRandomValue,Captain Teemo - pocketPet,someRandomValue
someRandomValue,Pinky Brain - Fictional,someRandomValue
someRandomValue,Miyamoto Musashi - swordsman,someRandomValue
someRandomValue,Kato yasunori - troubleMaker - Extreme,someRandomValue

给定以下代码:

注意:我知道数组值是正确的,我只需要知道如何循环访问表达式中的数组。

$firstNames = @()
$firstNameCounter = 0
$lastNames = @()
$lastNameCounter = 0

Import-Csv $file1 | 
    foreach { 
        $firstNames += $_.Description.split(" ")[0]
        $lastNames += $_.Description.split(" ")[1]
    }

Import-Csv $file1 |
    Select-Object  *, @{n='First Name'; e={$firstNames[$firstNameCounter];$script:firstNameCounter++}}, @{n='Last Name'; e={$lastNames[$lastNameCounter];$script:lastNameCounter++}} | 
    Export-Csv "testresults.csv" -NoTypeInformation -Force

我每次只获取数组中的第一个元素。因此,最终结果文件如下所示

column1,columnICareAbout,column2,First Name,Last Name
someRandomValue,John Doe - Generic,someRandomValue,John,Doe
someRandomValue,Captain Teemo - pocketPet,someRandomValue,John,Doe
someRandomValue,Pinky Brain - Fictional,someRandomValue,John,Doe
someRandomValue,Miyamoto Musashi - swordsman,someRandomValue,John,Doe
someRandomValue,Kato yasunori - troubleMaker - Extreme,someRandomValue,John,Doe

我希望文件如下所示

column1,columnICareAbout,column2,First Name,Last Name
someRandomValue,John Doe - Generic,someRandomValue,John,Doe
someRandomValue,Captain Teemo - pocketPet,someRandomValue,Captain,Teemo
someRandomValue,Pinky Brain - Fictional,someRandomValue,Pinky,Brain
someRandomValue,Miyamoto Musashi - swordsman,someRandomValue,Miyamoto,Musashi
someRandomValue,Kato yasunori - troubleMaker - Extreme,someRandomValue,Kato,yasunori

有人能告诉我我做错了什么吗?

推荐答案

Import-Csv $file1 | 
foreach { 
    $firstName = $_.Description.split(" ")[0]
    $lastName = $_.Description.split(" ")[1]

    $_ | Add-Member -MemberType NoteProperty -Name FirstName -Value $firstName
    $_ | Add-Member -MemberType NoteProperty -Name LastName -Value $lastName
} | Export-Csv 'results.csv'

添加成员命令将追加FirstName和LastName两列

这篇关于PowerShell将CSV列值拆分为两个独立的列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 03:20