简体   繁体   English

如何删除Powershell中的第一行和最后一行

[英]How to remove First and Last Line in Powershell

This script will do some processing on csv file notably removing first line (subsequent to How to export to "non-standard" CSV with Powershell ) : 此脚本将对csv文件进行一些处理,特别是删除第一行(在如何使用Powershell导出为“非标准”CSV之后 ):

Import-Csv in.csv -header Date,Time,O,H,L,C,V|select * -ExcludeProperty time|
%{$_.date = [datetime]::ParseExact($_.date,"yyyy.MM.dd",$null).tostring("yyMMdd");$_.v=1;$_}|
ConvertTo-Csv -NoTypeInformation|
select -skip 1|
%{$_ -replace '"'}|
Set-Content out.csv -encoding ascii

Now I need to refine it by also removing last line. 现在我需要通过删除最后一行来改进它。 I tried to add : 我试着添加:

select -skip ($_.Count - 1) select -skip($ _。Count - 1)

but it generates exception. 但它会产生异常。

So what the right syntax ? 那么正确的语法是什么?

Depending on the version of PowerShell you have, you can use the -SkipLast parameter, eg: 根据您拥有的PowerShell版本,您可以使用-SkipLast参数,例如:

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

SkipLast is available for PowerShell 5.0 and higher. SkipLast适用于PowerShell 5.0及更高版本。

If you don't have that parameter, you can install it via the Microsoft Website. 如果您没有该参数,可以通过Microsoft网站进行安装。 Windows 7 is the earliest OS version that can run PowerShell 5. Windows 7是最早可以运行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
}

If you cannot run -SkipLast because you don't have Powershell 5, rather than using a for loop, I would suggest using this : 如果你不能运行-SkipLast,因为你没有Powershell 5,而不是使用for循环,我建议使用它:

$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. 然后,你必须对你的$ csv变量(长度等)进行一些检查,添加你的set-content代码,它应该可以正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM