简体   繁体   English

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

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

I am using the following script to iterate through a list of files in a folder, then it will regex search for a string containing the 'T|0-9' which is the trailer record and will be present at the end of each 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

}

This script works fine, however, it may take a long time to go through large file, I therefore used the '-tail 5' parameter so that it will start searching from the last 5 lines, the problem is that it is deleting everything and only leaving the last lines in the feed. 这个脚本工作正常,但是,可能需要很长时间才能通过大文件,因此我使用'-tail 5'参数,以便它将从最后5行开始搜索,问题是它正在删除所有内容和只留下Feed中的最后一行。

Is there any other way to acomplish this? 有没有其他方法来实现这个?

I tried another sample code I found but it doesnt really work, can someone guide me please 我尝试了另一个我找到的示例代码,但它并没有真正起作用,请有人指导我

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

Since Get-Content returns an array , you can access the last item (last line) using [-1] : 由于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