Powershell 根据参数在文件中搜索字符串

Powershell search strings in a file according to arguments

我有一个包含多个单词的文件。我只想得到那些包含我作为参数传递给程序的字母的单词。

例如:test.txt

apple
car
computer
tree

./select.ps1 test.txt o e r

结果应该是这样的:

computer

我写了这个:

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

但是如果我想使用例如 10 个参数并且不想一直更改我的代码怎么办?我该如何处理?

我会看一看 this and this

我还想指出:

Select-String 能够一次搜索具有多个模式的多个项目。您可以通过将要匹配的字母保存到变量并用一行检查所有字母来利用它。

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

这将 return 输出如下:

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

只获取匹配的词:

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

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

您需要两个循环:一个处理输入文件的每一行,另一个将当前行与每个过滤器字符匹配。

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

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

请注意,如果您想一次匹配比单个字符更复杂的表达式,这将需要做更多的工作。

建议一些不同的东西,只是为了好玩:

$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"

您可能希望使用文件加载 $Items 变量:

$Items = Get-Content $file