2015-05-05 29 views
3

我有一个包含多个单词的文件。我只想得到那些包含我作为参数传递给程序的字母的单词。Powershell根据参数在文件中搜索字符串

例如: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个参数并且不想一直改变我的代码呢?我将如何管理?

回答

3

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

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

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

请注意,如果要匹配比一次只有一个字符更复杂的表达式,则需要更多的工作。

-2

我会看看thisthis

我也想指出:

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 
+0

的OP明确表示,他希望得到的结果是只是“计算机”(即他只想匹配包含*全部*给定字符的行,而不是匹配*任何*行的行)。 –

+0

你说得对,我应该仔细阅读。 – StegMan

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 = Get-Content $file