2017-03-15 34 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-工作)。 –