3

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?

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

-2

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

1 Comment

The OP expressly stated that he wants the result to be just computer (i.e. he wants to match only lines that contain all of the given characters, not lines that match any of them).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.