How to remove First and Last Line in Powershell

后端 未结 2 1800
醉酒成梦
醉酒成梦 2020-12-21 17:10

This script will do some processing on csv file notably removing first line (subsequent to How to export to "non-standard" CSV with Powershell ) :

         


        
相关标签:
2条回答
  • 2020-12-21 17:35

    Depending on the version of PowerShell you have, you can use the -SkipLast parameter, e.g.:

    ... | Select -Skip 1 | Select -SkipLast 1
    

    SkipLast is available for PowerShell 5.0 and higher.

    If you don't have that parameter, you can install it via the Microsoft Website. Windows 7 is the earliest OS version that can run PowerShell 5.

    If that's not possible, use:

    $csv = Import-Csv in.csv -header Date,Time,O,H,L,C,V | `
           Select * -ExcludeProperty time | `
           Foreach {$_.date = [datetime]::ParseExact($_.date,"yyyy.MM.dd",$null).tostring("yyMMdd");$_.v=1;$_} | `
           ConvertTo-Csv -NoTypeInformation
    
    for ($i = 1; $i -lt ($csv.Length - 1); $i++) { 
        $csv[$i] -replace '"' | Add-Content out.csv -encoding ascii
    }
    
    0 讨论(0)
  • 2020-12-21 17:51

    If you cannot run -SkipLast because you don't have Powershell 5, rather than using a for loop, I would suggest using this :

    $csv[1..$($csv.Count - 2)]
    

    This way, you will skip the first and last line. Then, you must do some checks on your $csv variable (length, etc.) add your set-content code, and it should work fine.

    0 讨论(0)
提交回复
热议问题