Powershell find common strings varying number of a

2019-09-19 12:16发布

问题:

Question is a follow up to Powershell find common string in multiple files

Following PowerShell code

  1. goes through a directory

  2. for each file, extract IP addresses and store in multi-dimensional array $match

  3. after iteration, go through each element in the multi-dimensional array and split by space, and store into another multi-dimensional array $j

I am able to find the intersection between $j[0] and $j[1], but I'm not sure how to do this iteratively, over all the elements of $j, the array of IP address arrays.

See code

$i = $NULL
$match = @()
$j = @()
$input_path = $NULL
$output_file = "D:\Script\COMMON.TXT"

$directory = "D:\Script\Files"
$regex = ‘\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b’

Get-ChildItem $directory | ForEach-Object{

    $input_path = $directory + "\" + $_.Name
    write-host $input_path
    $match += ,@(select-string -Path $input_path -Pattern $regex -AllMatches | % { $_.Matches } | % { $_.Value })
}



foreach ($i in $match){
    $j += ,@($i.split(" "))
}

$j[0] | sort | select -Unique | where {$j[1] -contains $_} | select -Unique > $output_file

回答1:

This is easy. You say you have two-dimensional array $j and want to find all strings that exist in all elements of $j. You create a temporary "total intersection" array out of $j[0] then run foreach on $j and create an intersection into that temporary. At the end it'll only contain those elements that all of the columns contain.

# $j is two-dimensional, and has unique elements
$t=$j[0]
$j | % {
    $i=$_ #rename to avoid confusion
    if ($i -ne $j[0]) { $t = $t|where {$i -contains $_}}
}
# $t now has your intersection