3

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

例如:test.txt

apple
car
computer
tree

./select.ps1 test.txt oer

结果应该是这样的:

computer

我写了这个:

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

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

4

3 回答 3

3

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

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

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

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

于 2015-05-05T17:14:15.093 回答
0

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

$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
于 2015-05-05T21:58:31.843 回答
-2

我会看看这个这个

我还想指出:

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

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

这将返回如下输出:

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
于 2015-05-05T17:00:48.250 回答