Home > Software engineering >  Remove characters from IP address
Remove characters from IP address

Time:02-10

Thanks to @SantiagoSquarzon, I have a code which is comparing csv where few of the IP addresses are like 10.124.94.132 fe80::80fe:f4a7:b182:82e1

So when I am doing the comparison, it is returning wrong value.

below is my code

$CSV1 = Import-Csv -Path 'E:\IP_Details.csv'
$reference = [System.Collections.Generic.HashSet[string]]::new(
    [string[]](Import-Csv -Path 'E:\IP_Details_1.csv').'IP adress'.ForEach('Trim')
)

$results = foreach($line in $Csv1)
{
    $ip = $line.'IP adress'.Trim()
    [PSCustomObject]@{
        Value   = $ip
        IPName  = $line.IPName
        Results = ('Not Match', 'Match')[$reference.Contains($ip)]
    }
}

$results | Export-Csv -Path "E:\File.csv" -NoTypeInformation

Please let me know how to remove the characters so that it should not affect the comparison.

CodePudding user response:

I think you have a combination of IPV4 and IPV6 addresses in there every now and then.

To exclude those in your comparison, I would do:

$Csv1      = Import-Csv -Path 'E:\IP_Details.csv'
# get an array of IPV4 addresses from the reference file
$reference = Import-Csv -Path 'E:\IP_Details_1.csv' | ForEach-Object {
                ([regex]'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}').Match($_.'IP adress').Value
             } | Sort-Object -Unique

$result = foreach($line in $Csv1) {
    # get the IPV4 address from the field
    $ip = ([regex]'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}').Match($line.'IP adress').Value
    [PSCustomObject]@{
        Value   = $ip
        IPName  = $line.IPName     # don't know what is in here..
        Results = $reference -contains $ip
    }
}

$result | Export-Csv -Path "E:\File.csv" -NoTypeInformation
  • Related