Powershell search strings in file by arguments

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

For example: test.txt

apple
car
computer
tree

      

./select.ps1 test.txt oer

The result should look like this:

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 should I do it?

+3


source to share


3 answers


You need two loops: one to process each line of the input file and the other to process the current line for 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 requires additional work if you want to combine expressions more complex than just one character at a time.

+3


source


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 want to load the $ Items variable with the file:

$Items = Get-Content $file

      

0


source


I would look at this and this ,

I also wanted to point out:

Select-String

able to search for more than one element with more than one pattern at a time. You can use this to your advantage by storing the letters you want to map to the variable and validate them all with one line.

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

      

This will return the output, for example:

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

      

To get only words that match:

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

      

or

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

      

-2


source







All Articles