2017-03-15 12 views
0

でどこ-オブジェクトで複数の条件を使用する:は、次のテキストファイルから単語<strong>ピザ</strong>を含む行を削除するには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は、次のスクリプトは、ド・モルガンの法則PowerShellでtruth table(ナイーブ)の実装を提起

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

として否定条件を書き換えることができ

'' 
'{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

パイプが-Orのように動作するので、Where-Object {$_ -notmatch 'this|that'}は複数の条件にマッチするより良い方法です。

$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-作業)。 –

関連する問題