2017-03-15 33 views
0

位置对象不止一个条件要删除包含单词比萨饼从下面的文本文件中的行:使用与在PowerShell中

The cat is my favorite animal. 
I prefer pizza to vegetables. 
My favorite color is blue. 
Tennis is the only sport I like. 
My favorite leisure time activity is reading books.

我跑了下面的代码,并将其成功地删除第二行。

$inputFile = "C:\Temp\Text.txt" 
Get-Content $inputFile | Where-Object {$_ -notmatch 'pizza'} | Set-Content "C:\Temp\Filtered.txt" 

不过,我还没有找到一种方法来去除包含的所有行或者字比萨饼或单词运动。我试过这个代码来做到这一点:

$inputFile = "C:\Temp\Text.txt" 
Get-Content $inputFile | Where-Object {$_ -notmatch 'pizza' -or $_ -notmatch 'sport'} | Set-Content "C:\Temp\Filtered.txt" 

但作为输出文件是一样的原来这是行不通的。

+1

如果你不想匹配要么你需要使用'-and'不'-or'。否则,你只能过滤比萨饼和运动。 – BenH

+0

- 而不是 - 或。 – tommymaynard

+3

我发现'Where-Object {$ _ -notmatch'pizza | sport'}'是匹配多个条件的更好方法 –

回答

0

你需要让自己清除逻辑

首先,使用积极条件得到都在我的文本文件中的行是包含单词“比萨饼” 字“运动”:

Get-Content $inputFile | Where-Object {$_ -match 'pizza' -or $_ -match 'sport'} 

输出应该是

I prefer pizza to vegetables. 
Tennis is the only sport I like. 

然后,否定病情得到期望的结果:

Get-Content $inputFile | Where-Object { -NOT ($_ -match 'pizza' -or $_ -match 'sport') } 

De Morgan's laws允许改写否定条件为

Get-Content $inputFile | Where-Object { $_ -NOTmatch 'pizza' -AND $_ -NOTmatch 'sport' } 

下面的脚本造成在PowerShell中truth table(幼稚)实现的德摩根定律

'' 
'{0,-6} {1,-6}: {2,-7} {3,-7} {4,-7} {5,-7}' -f 'P', 'Q', 'DM1a', 'DM1b', 'DM2a', 'DM2b' 
'' 
ForEach ($P in $True, $False) { 
    ForEach ($Q in $True, $False) { 
     '{0,-6} {1,-6}: {2,-7} {3,-7} {4,-7} {5,-7}' -f $P, $Q, 
      (-not ($P -and $Q) -eq (  ((-not $P) -or (-not $Q)))), 
      (  ($P -and $Q) -eq (-not ((-not $P) -or (-not $Q)))), 
      (-not ($P -or $Q) -eq (  ((-not $P) -and (-not $Q)))), 
      (  ($P -or $Q) -eq (-not ((-not $P) -and (-not $Q)))) 
    } 

} 

输出(注意:DM2a列涵盖的情况下):

PS D:\PShell> D:\PShell\tests\DeMorgan.ps1 

P  Q  : DM1a  DM1b  DM2a  DM2b 

True True : True  True  True  True 
True False : True  True  True  True 
False True : True  True  True  True 
False False : True  True  True  True 
+0

哦!我知道了。感谢您花时间写下这个长长的解释。很有帮助。 – blouskrine

+0

不客气,我的荣幸。 – JosefZ

3

我觉得Where-Object {$_ -notmatch 'this|that'}是一个更好的匹配多个条件的方法,因为管道的作用就像-Or

$inputFile = "C:\Temp\Text.txt" 
Get-Content $inputFile | Where-Object {$_ -notmatch 'pizza|sport'} | Set-Content "C:\Temp\Filtered.txt" 
+0

它的作品,它更优雅!谢谢你的帮助。 – blouskrine

+0

您也可以使用-in运算符来测试数组中是否存在您的值。 –

+0

@blouskrine很高兴我可以帮助:)如果您满意我的答案,您可以[将其标记为已接受](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-工作)。 –