Mike
Mike

Reputation: 3

In Powershell: Remove lines from a text file if it contains a set words stored in another text file

I know:

Get-Content C:\new\temp_*.txt | Select-String -pattern "H|159" -notmatch | Out-File C:\new\newfile.txt

But i need to fetch -pattern from another text file as the patterns are 300k so cannot be piped.

What is the modified command?

Upvotes: 0

Views: 108

Answers (2)

Mike
Mike

Reputation: 3

$pattern = Get-Content fileWithRegexPattern.txt; Get-Content text.txt |Select-String -Pattern $pattern

and pipe the output.

Upvotes: 0

Steven
Steven

Reputation: 7067

Pattern will take an array of patterns, which can just as easily be the result of Get-Content of another file. Select-String emits objects, so if your're hoping the matched lines are going to be in he file it's going to be wrong.

In that case it will show the filename the line number and the matched line.

To get just the lines try something like:

$Pattern = Get-Content <SomeFile.txt>
(Select-String -path C:\new\temp_*.txt -Pattern $pattern).Line | Out-File C:\new\newfile.txt
  • Establishing the $Pattern variable as an array of patterns sourced from a file
  • Instead of piping the files to select string use the -Path parameter with the wildcard pattern.
  • Then reference & pipe the line property of the match objects instead of piping the objects themselves to the file.

This will result in only the matching lines being present in the output file.

let me know if that helps.

Upvotes: 1

Related Questions