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