使用PowerShell删除文本文件中包含字符串的行

xzlaal3s  于 2023-01-13  发布在  Shell
关注(0)|答案(7)|浏览(137)

我正在尝试使用下面的PowerShell代码从包含部分字符串的文本文件中删除所有行:

Get-Content C:\new\temp_*.txt | Select-String -pattern "H|159" -notmatch | Out-File C:\new\newfile.txt

实际的字符串是H|159|28-05-2005|508|xxx,它在文件中重复了多次,并且我尝试只匹配上面指定的第一部分。对吗?目前我的输出为空。
我错过什么了吗?

anauzrmj

anauzrmj1#

假设你想把它写在同一个文件中,你可以做如下:

Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)
bvpmtnay

bvpmtnay2#

逃离|使用反勾号的字符

get-content c:\new\temp_*.txt | select-string -pattern 'H`|159' -notmatch | Out-File c:\new\newfile.txt
u0njafvf

u0njafvf3#

在这种情况下,不需要Select-String,只需使用Where-Object过滤掉这些行即可

Get-Content C:\new\temp_*.txt |
    Where-Object { -not $_.Contains('H|159') } |
    Set-Content C:\new\newfile.txt

String.Contains执行字符串比较而不是正则表达式比较,因此不需要转义管道字符,而且速度也更快

n3h0vuf2

n3h0vuf24#

管道字符|在正则表达式中有特殊的含义。a|b表示“匹配ab“。如果要匹配文本|字符,则需要对其进行转义:

... | Select-String -Pattern 'H\|159' -NotMatch | ...
o2g1uqev

o2g1uqev5#

另一个写入相同文件的选项,基于现有答案。只需添加括号以在内容发送到文件之前完成操作。

(get-content c:\new\sameFile.txt | select-string -pattern 'H`|159' -notmatch) | Set-Content c:\new\sameFile.txt
1tuwyuhd

1tuwyuhd6#

这可能是一个很长的路要走围绕一个简单的问题,它确实允许我删除行包含大量的匹配。我没有一个部分匹配,可以使用,并需要它被做超过1000个文件。这篇文章确实帮助我到达我需要的地方,谢谢。

$ParentPath = "C:\temp\test"
$Files = Get-ChildItem -Path $ParentPath -Recurse -Include *.txt
$Match2 = "matchtext1"
$Match2 = "matchtext2"
$Match3 = "matchtext3"
$Match4 = "matchtext4"
$Match5 = "matchtext5"
$Match6 = "matchtext6"
$Match7 = "matchtext7"
$Match8 = "matchtext8"
$Match9 = "matchtext9"
$Match10 = "matchtext10"

foreach ($File in $Files) {
    $FullPath = $File | % { $_.FullName }
    $OldContent = Get-Content $FullPath
    $NewContent = $OldContent `
    | Where-Object {$_ -notmatch $Match1} `
    | Where-Object {$_ -notmatch $Match2} `
    | Where-Object {$_ -notmatch $Match3} `
    | Where-Object {$_ -notmatch $Match4} `
    | Where-Object {$_ -notmatch $Match5} `
    | Where-Object {$_ -notmatch $Match6} `
    | Where-Object {$_ -notmatch $Match7} `
    | Where-Object {$_ -notmatch $Match8} `
    | Where-Object {$_ -notmatch $Match9} `
    | Where-Object {$_ -notmatch $Match10}
    Set-Content -Path $FullPath -Value $NewContent
    Write-Output $File
}
6ju8rftf

6ju8rftf7#

如果你有任何人有这个问题,而做什么建议的Robert Brooker-
*These files have different encodings. Left file: Unicode (UTF-8) with signature. Right file: Unicode (UTF-8) without signature. You can resolve the difference by saving the right file with the encoding Unicode (UTF-8) with signature.*Set-Content
使用-Encoding UTF8
就像这样

(get-content c:\new\sameFile.txt | select-string -pattern 'H`|159' -notmatch) | Set-Content c:\new\sameFile.txt -Encoding UTF8

相关问题