使用 powershell 删除文件中的特定行

Sys*_*her 2 windows csv powershell file

我想删除 powershell 脚本中单个 .csv 文件中包含特殊单词的完整行。

我已经找到了工作代码,它删除了特定行,但将所有其他行写入第一行。这不应该发生,因为我将 csv 文件与 ms 访问表链接起来。

    $user = 'User2'
    $file = Get-Content c:\datei.txt
    $newLine = ""

    foreach($line in $file){

        if($line -match $User){
         }else{
            $newLine += $line
        }
    }
    $newLine | Out-File c:\datei.txt
Run Code Online (Sandbox Code Playgroud)

该文件如下所示,但包含更多数据和行:

User;computer;screen1;screen2;printer
User1;bla;bla;;bla
User2;bla;bla;bla;bla
User3;bla;bla;bla;bla
Run Code Online (Sandbox Code Playgroud)

运行代码后:

User;computer;screen1;screen2;printerUser1;bla;bla;;blaUser3;bla;bla;bla;bla
Run Code Online (Sandbox Code Playgroud)

我在 Windows 7 上使用 Powershell 5.1.x

Tes*_*ler 6

发生这种情况是因为您正在进行字符串连接。

$newLine = ""
$newLine += $line

# result is exactly how it looks,  
# "" -> "line1" -> "line1line2" -> "line1line2line3" ...
Run Code Online (Sandbox Code Playgroud)

直接的解决方法是使用数组:

$newLine = @()
$newLine += $line

# result is adding lines to an array  
# @() -> @("line1") -> @("line1","line2") -> @("line1","line2","line3") ...
Run Code Online (Sandbox Code Playgroud)

但正确的 PowerShell 方法是根本不这样做,而是通过代码流式传输文件并将其输出到另一个文件中:

$user = 'User2'
$file = Get-Content c:\datei.txt

foreach($line in $file){

    if($line -match $User){
     }else{
        $line   # send the line to the output pipeline
    }

} | Out-File c:\datei.txt
Run Code Online (Sandbox Code Playgroud)

-match但您可以反转测试-notmatch并去掉空白{}部分。

$user = 'User2'
$file = Get-Content c:\datei.txt

foreach($line in $file){

    if($line -notmatch $User){
        $line   # send the line to the output pipeline
    }

} | Out-File c:\datei.txt
Run Code Online (Sandbox Code Playgroud)

并且您可以摆脱临时存储文件内容:

$user = 'User2'
Get-Content c:\datei.txt | ForEach-Object {

    if ($_ -notmatch $User){
        $line   # send the line to the output pipeline
    }

} | Out-File c:\datei.txt
Run Code Online (Sandbox Code Playgroud)

但它只是充当过滤器,您可以更改foreach-object / if() {}where-object过滤器:

$user = 'User2'
Get-Content c:\datei.txt | Where-Object {

    $_ -notmatch $User

} | Out-File c:\datei.txt
Run Code Online (Sandbox Code Playgroud)

然后更改Out-fileSet-Content(配对是 get-content/set-content,如果需要,它可以更好地控制输出编码):

$user = 'User2'

Get-Content c:\datei.txt | 
    Where-Object { $_ -notmatch $User } | 
    Set-Content c:\datei.txt
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。我尝试了你最后的建议,它也有效。我只需要添加括号,因为它表示该文件已在使用` (Get-Content c:\datei.txt |Where-Object { $_ -notmatch $User }) | 设置内容 c:\datei.txt ` (2认同)