powershell - 使用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
解决方案
您提供的 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,但这更容易编写。
推荐阅读
- colorfilter - 去马赛克 RCCB 彩色滤光片阵列
- javascript - 无论光标或焦点在哪里,如何在 10 秒后关闭自动完成菜单?
- javascript - wavesurfer getPeaks 返回一个空数组
- flutter - 将文件上传到 Flutter web 上的 Parse Server
- android - Kotlin - 在活动重启时保留 RecyclerView 位置
- python-3.x - 将核苷酸序列转换为二维整数数组
- vba - 排列形状以使边缘重合 Visio VBA
- typescript - 如何将 firestores 类型导入 utils 文件?
- tensorflow - 如何在 Tensorflow 中的 Dataset 对象中显示类分布
- swift - 为什么 CALayer 没有被添加到 UITextView