簡體   English   中英

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

[英]delete a specific line in file with powershell

我想刪除一整行,其中包含在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

該文件如下所示,但具有更多數據和更多行:

User;computer;screen1;screen2;printer
User1;bla;bla;;bla
User2;bla;bla;bla;bla
User3;bla;bla;bla;bla

運行代碼后:

User;computer;screen1;screen2;printerUser1;bla;bla;;blaUser3;bla;bla;bla;bla

我在Windows 7上使用Powershell 5.1.x

發生這種情況是因為您正在執行字符串連接。

$newLine = ""
$newLine += $line

# result is exactly how it looks,  
# "" -> "line1" -> "line1line2" -> "line1line2line3" ...

最直接的解決方法是使用數組:

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

# result is adding lines to an array  
# @() -> @("line1") -> @("line1","line2") -> @("line1","line2","line3") ...

但是正確的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

但是您可以將test -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

您可以擺脫臨時存儲文件內容的麻煩:

$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

但是,它只是充當過濾器,您可以將foreach-object / if() {}更改為where-object過濾器:

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

    $_ -notmatch $User

} | Out-File c:\datei.txt

然后將Out-file更改為Set-Content (配對為get-content / set-content,如果需要,它可以更好地控制輸出編碼):

$user = 'User2'

Get-Content c:\datei.txt | 
    Where-Object { $_ -notmatch $User } | 
    Set-Content c:\datei.txt

您需要在每行文本的末尾添加“換行符”。 更改此行:

$newLine += $line

至:

$newLine += "$line`r`n"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM