在Powershell中从file1中删除存在于file2中的行 [英] Remove lines from file1 that exist in file2 in Powershell

查看:85
本文介绍了在Powershell中从file1中删除存在于file2中的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个file1.txt,其中包含:

I have a file1.txt which contains:

第1行
第2行
第3行
第4行

line1
line2
line3
line4

我想从file1.txt中删除另一个file2.txt中存在的所有行:

I want to remove from file1.txt all the lines which exist in another file2.txt:

line3
第2行

line3
line2

结果应为:

第1行
第4行

line1
line4

我尝试使用此命令,但是只有在file2.txt中有一行时,它才有效:

I tried to use this command but it works only if I have one line in file2.txt :

Get-Content C:\file1.txt | Where-Object {$_ -notmatch $(get-content C:\file2.txt)} 

注意:我不想比较2个文件以查看它们是否相同.

Note : I don't want to compare 2 files to see if they are the same.

有什么主意吗?我对Powershell相当陌生.

Any idea? I'm pretty new to powershell.

推荐答案

下一个代码段显示了两种实现相同结果的不同方法:

Next code snippet shows two different ways to achieve the same result:

$filebefore="$env:TEMP\beforerestart.txt"    # change to match your circumstances
$file_after="$env:TEMP\after_restart.txt"    # ditto

### Compare-Object way
$array = Compare-Object $(Get-Content $filebefore) $(Get-Content $file_after)
$array | where {$_.SideIndicator -eq "<="} | 
              Format-Table -Property InputObject -AutoSize -HideTableHeaders

### -NotIn operator way
$(Get-Content $filebefore) | 
     Where-Object {$_ -notIn $(Get-Content $file_after)} 

这篇关于在Powershell中从file1中删除存在于file2中的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆