Joe
Joe

Reputation: 33

Powershell search strings in a file according to arguments

I have a file with multiple words. I would like to get only those words, that contain the letters I passed as arguments to the program.

For example: test.txt

apple
car
computer
tree

./select.ps1 test.txt o e r

Result should be like:

computer

I wrote this:

foreach ( $line in $args[0] ) {
        Get-Content $line | Select-String -Pattern $args[1] | Select-String -Pattern $args[2] | Select-String $args[3]
}

But what if I want to use for example 10 parameters and don't want to change my code all the time? How would I manage that?

Upvotes: 3

Views: 627

Answers (3)

Marc Kellerman
Marc Kellerman

Reputation: 466

Suggesting something different, just for fun:

$Items = "apple", "car", "computer", "tree"

Function Find-ItemsWithChar ($Items, $Char) {
    ForEach ($Item in $Items) {
        $Char[-1..-10] | % { If ($Item -notmatch $_) { Continue } }
        $Item
    }
} #End Function Find-ItemsWithChar

Find-ItemsWithChar $Items "oer"

You would want to load up the $Items variable with you file:

$Items = Get-Content $file

Upvotes: 0

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200213

You need two loops: one to process each line of the input file, and the other to match the current line against each filter character.

$file = 'C:\path\to\your.txt'

foreach ($line in (Get-Content $file)) {
  foreach ($char in $args) {
    $line = $line | ? { $_ -like "*$char*" }
  }
  $line
}

Note that this will need some more work if you want to match expressions more complex than just a single character at a time.

Upvotes: 3

StegMan
StegMan

Reputation: 531

I would take a look at this and this.

I also wanted to point out:

Select-String is capable of searching more than one item with more than one pattern at a time. You can use this to your advantage by saving the letters that you want to match to a variable and checking all of them with one line.

$match = 'a','b','c','d','e','f'
Select-String -path test.txt -Pattern $match -SimpleMatch

This will return output like:

test.txt:1:apple
test.txt:2:car
test.txt:3:computer
test.txt:4:tree

To get just the words that matched:

Select-String -Path test.txt -Pattern $match -SimpleMatch | Select -ExpandProperty Line

or

(Select-String -Path test.txt -Pattern $match -SimpleMatch).Line

Upvotes: -2

Related Questions