问题描述
此脚本将对 csv 文件进行一些处理,特别是删除第一行(在 如何使用 Powershell 导出到非标准"CSV):
This script will do some processing on csv file notably removing first line (subsequent to How to export to "non-standard" CSV with Powershell ) :
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)
但它会产生异常.
那么正确的语法是什么?
So what the right syntax ?
推荐答案
根据您拥有的 PowerShell 版本,您可以使用 -SkipLast
参数,例如:
Depending on the version of PowerShell you have, you can use the -SkipLast
parameter, e.g.:
... | Select -Skip 1 | Select -SkipLast 1
SkipLast
适用于 PowerShell 5.0 及更高版本.
SkipLast
is available for PowerShell 5.0 and higher.
如果您没有该参数,则可以通过 Microsoft 网站进行安装.Windows 7 是最早可以运行 PowerShell 5 的操作系统版本.
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.
如果不可能,请使用:
$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
}
这篇关于如何删除Powershell中的第一行和最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!