Finding a variable text in another textfile and get the containing line

Hello there,

quite new to Powershell, i’m struggling with the following problem and im not finding any good answer in the interwebs.

I have a textfile “ID.txt” containing lines with IDs in form of “SBS1234568” in variable length.

I have another textfile “IPs.txt” containing lines with IP adresses and the mentioned ID above separated by “;” aka “10.55.0.0/24 ; SBS1234568”

I now want to find IDs listet in “id.txt” in “IPs.txt” and get the entire line from “IPs.txt” to output it to another file.

I tried with a foreach and IF but I was not able to get it anywhere near…

EDIT:
This is what I tried so far:

$IPs = Get-Content IPs.txt
$ID = Get-Content ID.txt
Foreach ($line in $ID) {
IF (Select-String $IPs -Pattern "$line") {
Continue;
}
$new_ip = $line | out-file -FilePath new_ips.txt;
}

 

Any help would be very much appreciated!

regards blitzdesigner

When you crosspost the same question at the same time to different forums you should at least post links to the other forums along with your question to avoid people willing to you help making their work twice or more.

https://stackoverflow.com/questions/63981336/finding-a-variable-text-in-another-textfile-and-get-the-containing-line

Thanks

you are right, sorry :slight_smile:

For completeness I am providing the same answer I shared on StackOverflow.com here.

You can use Select-String on the IPs.txt file but one important thing you’re missing is your text in ID.txt is in this format

"SBS1234568"

Therefore when you’re trying to match a line in IPs.txt, it is effectively this

“10.55.0.0/24 ; SBS1234568” -match “SBS1234568” # this is $false

You’d have to remove at least the first quote, but instead of doing all that I would treat it as a CSV.

$idfile    = New-TemporaryFile
$ipfile    = New-TemporaryFile
$newipfile = 'c:\temp\new_ips.txt'

@'
"SBS1234568"
"SBS345689123"
"SBS87654"
"SBS87612354"
'@ | Set-Content $idfile -Encoding utf8

@'
"10.55.0.0/24 ; SBS1234568"
"10.44.0.0/24 ; SBS345689123"
"10.33.0.0/24 ; SBS87654"
"10.22.0.0/24 ; SBS87612354"
"10.1.0.0/24 ; SB612354"
'@ | Set-Content $ipfile -Encoding utf8

Import-Csv $idfile -Header id | foreach {
    (Select-String $ipfile -Pattern $_.id).line
} | Set-Content $newipfile -Encoding utf8

Get-Content $newipfile

Output

“10.55.0.0/24 ; SBS1234568”
“10.44.0.0/24 ; SBS345689123”
“10.33.0.0/24 ; SBS87654”
“10.22.0.0/24 ; SBS87612354”