Powershell find common strings varying number of arrays

拥有回忆 提交于 2020-01-14 05:31:08

问题


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


来源:https://stackoverflow.com/questions/30604405/powershell-find-common-strings-varying-number-of-arrays

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!