簡體   English   中英

如何從Powershell腳本刪除文件的每一行

[英]How to Delete each line of the file from Powershell Script

我的檔案內容如下

123
234
345

我正在使用一個foreach循環來讀取文件的每一行。

我有一個要求:我想在foreach循環中刪除文件的每一行。

反正有沒有刪除foreach循環內的文件行?

這是我嘗試過的:

$source1 = "Y:\New Documents\test.txt"
foreach ($line in Get-Content $source1) {
    $find = $line
    (Get-Content $source1).replace($find,"") |
        Set-Content $source1
}

我能夠清除文件的內容,但我不知道如何制作大小為零的文件。

您要執行的操作稱為“截斷文件”。 PowerShell為此具有一個cmdlet:

Clear-Content $source1

如果要先進行一些處理:先進行處理, 然后清除文件:

Get-Content $source1 | ForEach-Object {
    # do stuff with content of $source1
}

Clear-Content $source1

如果存在要處理內容並使行處於一種或另一種情況的情況,則可以收集應保留在變量中的行並將其寫回到文件中:

$remains = Get-Content $source1 | ForEach-Object {
    if (<# some condition or other #>) {
        # do stuff with matching lines
    } else {
        # output back to pipeline
        $_
    }
}

# write $remains back to file if it's not empty, otherwise clear file
if ($remains) {
    $remains | Set-Content $source1
} else {
    Clear-Content $source1
}

暫無
暫無

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

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