我有两个csv文件:每个得到3列,我想比较第一列,如果匹配,它将复制其他列中的内容例如:
1 csv:
column1 column2 column3
aaa bla baba
ccc bla babab3
abc bla bababa3
2 csv:
column1 column4 column5
abc dla2 blabla2
ddd dla blabla
ccc dla1 blabla1
aaa dla1 blabla1
更新csv:
column1 column2 column3 column4 column5
aaa bla baba dla1 blabla1
ccc bla babab3 dla1 blabla1
abc bla bababa3 dla2 blabla2
谢谢,
# Import both CSV files.
$rowsA = Import-Csv 1.csv
$rowsB = Import-Csv 2.csv
# The name of the shared column to join by.
$sharedCol = 'Column1'
# Get the column names of 2.csv, excluding the shared one.
$colsB = $rowsB[0].psobject.Properties.Name -ne $sharedCol
# Create a map (hashtable) that maps the shared column
# values to the column values of the matching 2.csv rows.
$map = @{}
$rowsB.ForEach({ $map[$_.$sharedCol] = $_.psobject.Properties[$colsB] })
# Construct empty helper properties for those $sharedCol values in 1.csv
# that have no counterpart in 2.csv
$emptyPropsB =
([pscustomobject] @{} | Select-Object -Property $colsB).psobject.Properties
$rowsA | ForEach-Object {
$rowA = $_
# Find the matching 2.csv row's column values. If not found, use empty ones.
$colValuesB = $map[$rowA.$sharedCol]
if (-not $colValuesB) { $colValuesB = $emptyPropsB }
# Append the column values from the 2.csv row to the 1.csv row at hand.
$colValuesB.ForEach({ $rowA.psobject.Properties.Add($_) })
$rowA # Output the merged row.
} # | Export-Csv -NoTypeInformation -Encoding utf8 updated.csv
输出到显示器;从最后一行中删除#
以导出到CSV文件
注意:如果您想跳过没有匹配的2.csv行的1.csv行,请将if (-not $colValuesB) { $colValuesB = $emptyPropsB }
替换为if (-not $colValuesB) { return }
此外,您不需要$emptyPropsB = ...
语句。