簡體   English   中英

Powershell 3:刪除文本文件的最后一行

[英]Powershell 3: Remove last line of text file

我使用以下腳本迭代文件夾中的文件列表,然后它將正則表達式搜索包含'T | 0-9'的字符串,這是一個預告片記錄,並將出現在每個文本文件的末尾。

$path = "D:\Test\"
$filter =  "*.txt"
$files = Get-ChildItem -path $path -filter $filter

foreach ($item in $files)

{
            $search = Get-content $path$item
            ($search)| ForEach-Object { $_ -replace 'T\|[0-9]*', '' } | Set-Content $path$item

}

這個腳本工作正常,但是,可能需要很長時間才能通過大文件,因此我使用'-tail 5'參數,以便它將從最后5行開始搜索,問題是它正在刪除所有內容和只留下Feed中的最后一行。

有沒有其他方法來實現這個?

我嘗試了另一個我找到的示例代碼,但它並沒有真正起作用,請有人指導我

$stream = [IO.File]::OpenWrite($path$item)
$stream.SetLength($stream.Length - 2)
$stream.Close()
$stream.Dispose()

由於Get-Content返回一個array ,您可以使用[-1]訪問最后一項(最后一行):

foreach ($item in $files)
{
    $search = Get-content $item.FullName
    $search[-1] = $search[-1] -replace 'T\|[0-9]*', ''
    $search | Set-Content $item.FullName
}

暫無
暫無

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

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