繁体   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