首页 > 解决方案 > 使用powershell替换csv中的值

问题描述

我需要用 email.csv 用户 ID 中的电子邮件地址覆盖 userinfo.csv 中的电子邮件值,并且 u_user 值在两个 csv 中都匹配且唯一。userinfo.csv 中的电子邮件地址值不好,需要用 email.csv 中的电子邮件值覆盖。

如何匹配 csv 和附加电子邮件值中的用户 ID?

甚至不知道从哪里开始。任何帮助,请。

email.csv
userid,email
1234,user4@email.com
1235,user5@email.com

userinfo.csv
u_work,u_user,u_address,u_city,u_state,u_zip,u_email,u_phonehome
1234,here,there,everywhere,55555,1234@bad.org,555-555-5555
away,1235,there,here,everywhere,66666,1235@bad.com,666-666-6666

new.csv
u_work,u_user,u_address,u_city,u_state,u_zip,u_email,u_phonehome
1234,here,there,everywhere,55555,user4@email.com,555-555-5555
away,1235,there,here,everywhere,66666,user5@email.com,666-666-6666

标签: powershell

解决方案


您提供的 CSV 无效。标题行有 8 个字段。第 1 行有 7 个字段。那是无效的。我假设它应该看起来像这样:

userinfo.csv
u_work,u_user,u_address,u_city,u_state,u_zip,u_email,u_phone
home,1234,here,there,everywhere,55555,1234@bad.org,555-555-5555
away,1235,there,here,everywhere,66666,1235@bad.com,666-666-6666

换句话说,这u_phonehome实际上是u_phone并且home在您的示例中位于错误的行上。

您的基本步骤是:

A. 导email.csv入哈希表以便快速查找。

$emails = @{}
Import-Csv email.csv | ForEach-Object {
    $email[$_.userid] = $_.email
}

B. 导入userinfo.csv,并在必要时替换电子邮件地址。

$NewCSV = Import-Csv userinfo.csv | ForEach-Object {
    if ($emails.ContainsKey($_.u_user)) {
        $_.u_email = $emails[$_.u_user]
    }
    $_
}

C. 编写输出文件。

$NewCSV | Export-Csv new.csv -NoTypeInformation

您也可以使用 aSelect-Object和计算属性执行步骤 B,但这更容易编写。


推荐阅读