PowerShell脚本匹配2个文件和合并之间的字符串



我有2个包含字符串的文件,两个文件中的每个字符串均由冒号界定。两个文件共享一个通用字符串,我希望能够将两个文件(基于公共字符串)合并到1个新文件中。

示例:

File1.txt
tom:mioihsdihfsdkjhfsdkjf
dick:khsdkjfhlkjdhfsdfdklj
harry:lkjsdlfkjlksdjfsdlkjs
File2.txt
mioihsdihfsdkjhfsdkjf:test1
lkjsdlfkjlksdjfsdlkjs:test2
khsdkjfhlkjdhfsdfdklj:test3
File3.txt (results should look like this)
tom:mioihsdihfsdkjhfsdkjf:test1
dick:khsdkjfhlkjdhfsdfdklj:test3
harry:lkjsdlfkjlksdjfsdlkjs:test2
$File1 = @"
tom:mioihsdihfsdkjhfsdkjf
dick:khsdkjfhlkjdhfsdfdklj
harry:lkjsdlfkjlksdjfsdlkjs
"@
$File2 = @"
mioihsdihfsdkjhfsdkjf:test1
lkjsdlfkjlksdjfsdlkjs:test2
khsdkjfhlkjdhfsdfdklj:test3
"@
# You are probably going to want to use Import-Csv here
# I am using ConvertFrom-Csv as I have "inlined" the contents of the files in the variables above
$file1_contents = ConvertFrom-Csv -InputObject $File1  -Delimiter ":" -Header name, code # specifying a header as there isn't one provided
$file2_contents = ConvertFrom-Csv -InputObject $File2  -Delimiter ":" -Header code, test
# There are almost certainly better ways to do this... but this does work so... meh.
$results = @()
# Loop over one file finding the matches in the other file
foreach ($row in $file1_contents) {
    $matched_row = $file2_contents | Where-Object code -eq $row.code
    if ($matched_row) {
        # Create a hashtable with the values you want from source and matched rows
        $result = @{
            name = $row.name
            code = $row.code
            test = $matched_row.test
        }
        # Append the matched up row to the final result set
        $results += New-Object PSObject -Property $result
    }
}
# Convert back to CSV format, with a _specific_ column ordering
# Although you'll probably want to use Export-Csv instead
$results |
    Select-Object name, code, test |
    ConvertTo-Csv -Delimiter ":"

最新更新