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

时间:2018-12-18 07:29:31

标签: powershell

我有2个包含字符串的文件,两个文件中的每个字符串都用冒号分隔。这两个文件共享一个公用字符串,我希望能够将两个文件(基于公用字符串)合并为一个新文件。

示例:

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

1 个答案:

答案 0 :(得分:1)

$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 ":"