W Davis
W Davis

Reputation: 45

Matching lines in file from list

I have two text files, Text1.txt and Text2.txt

Text2.txt is a list of keywords, one keyword per line. I want to read from Text1.txt and any time a keyword in the Text2.txt list shows up, pipe that entire line of text to a new file, output.txt

Without using Text2.txt I figured out how to do it manually in PowerShell.

Get-Content .\Text1.txt | Where-Object {$_ -match 'CAPT'} | Set-Content output.txt

That seems to work, it searches for "CAPT" and returns the entire line of text, but I don't know how to replace the manual text search with a variable that pulls from Text2.txt

Any ideas?

Upvotes: 2

Views: 283

Answers (1)

Matt
Matt

Reputation: 46710

Using some simple regex you can make a alternative matching string from all the keywords in the file Text2.txt

$pattern = (Get-Content .\Text2.txt | ForEach-Object{[regex]::Escape($_)}) -Join "|"
Get-Content .\Text1.txt | Where-Object {$_ -match $pattern} | Set-Content output.txt

In case your keywords have special regex characters we need to be sure they are escaped here. The .net regex method Escape() handles that.

This is not an efficient approach for large files but it is certainly a simple method. If your keywords were all similar like CAPT CAPS CAPZ then we could improve it but I don't think it would be worth it depending how often the keywords change.

Changing the pattern

If you wanted to just match the first 4 characters from the lines in your input file that is just a matter of making a change in the loop.

$pattern = (Get-Content .\Text2.txt | ForEach-Object{[regex]::Escape($_.Substring(0,4))}) -Join "|"

Upvotes: 2

Related Questions