【问题标题】:Copy columns from one csv file to another using PowerShell使用 PowerShell 将列从一个 csv 文件复制到另一个
【发布时间】:2021-02-26 19:21:03
【问题描述】:

我有两个 csv 文件,每个文件有几列。

我想将 1.csv 列复制到 2.csv 文件。 例如: 1.csv 包含以下内容: 姓名,上次登录日期


user1 2020 年 15 月 11 日 用户 2 2020 年 12 月 11 日

2.csv 包含以下内容: 机器名、用户名、状态


win10-test1 tst1 可用 win10-test2 tst2 已连接

我想将 1.csv 文件列添加到 2.csv 文件或创建一个包含所有列的新 csv/excel 文件,如下所示: 名称、上次登录日期、机器名、用户名、状态


user1 2020 年 15 月 11 日 win10-test1 tst1 可用 user2 12/11/2020 win10-test2 tst2 已连接

(试图寻找解决方案但没有运气) 谢谢。

【问题讨论】:

  • 请解释 1.csv 中的列如何与 2.csv 中的列匹配,以便将正确的值放置在行中。 name 是否与 username 对应,如果是,如何?编辑您的问题并向我们展示每个 csv 文件的前 3 或 4 行(当然是经过清理的)
  • 嗨 Theo,由于某种原因,帖子上的文字弄乱了,所以我添加了一个带有示例的屏幕截图。谢谢
  • @Maor,使用问题文本框上方的 {}“代码示例”图标。见:How do I format my code blocks?
  • 但是是否有某种规则可以将user1 与用户名test1 匹配?

标签: excel powershell csv merge multiple-columns


【解决方案1】:

我建议以下解决方案,但从以下假设开始(否则由您来更正程序):

A.两个csv文件的分隔符是逗号

B. 两个文件之间的“连接”相当于 SQL 中的“左连接”。如果 2.csv 文件的行数比 1.csv 文件多,多余的行将被忽略

#get content of first csv with delimiter is coma
$Content1=import-csv "c:\temp\1.csv" -Delimiter ","

#get content of second csv with delimiter is coma
$Content2=import-csv "c:\temp\2.csv" -Delimiter ","

#get all columns to 2.csv
$MemberToGet=Get-Member -InputObject $Content2[0] -MemberType NoteProperty | sort Name

$i=-1

#For every row of 1.csv i take the same position row of content 2.csv and add all property and his value to current object, and finally export result
$Content1 | %{
$CurrentRowObject=$_
$i++
$MemberToGet | %{
                    $Name=$_.Name
                    Add-Member -InputObject $CurrentRowObject -MemberType NoteProperty -Name $Name -Value $Content2[$i]."$Name"
                 }

#send to output the result object
$CurrentRowObject


} | export-csv "c:\temp\3.csv" -NoType

【讨论】:

  • 终于成功了!非常感谢。
【解决方案2】:

你也可以使用 Join-object 命令:

#import 1.csv and add Index counter column as Key
$i=0
$Content1=import-csv "c:\temp\1.csv" -Delimiter "," | %{$i++;Add-Member -InputObject $_ -MemberType NoteProperty -Name "Index" -Value $i; $_}


#import 2.csv and add Index counter column as Key
$i=0
$Content2=import-csv "c:\temp\2.csv" -Delimiter "," | %{$i++;Add-Member -InputObject $_ -MemberType NoteProperty -Name "Index" -Value $i; $_}

#join csv files on Index Key => modify parameter Type for equijointure if necessary
Join-Object -Left $Content1 -Right  $Content2 -LeftJoinProperty "Index" -RightJoinProperty "Index" -Type AllInLeft | Export-Csv "c:\temp\3b.csv" -Delimiter "," -NoType

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-21
    • 2022-01-04
    • 1970-01-01
    • 2021-06-29
    • 2018-09-29
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    相关资源
    最近更新 更多