使用PowerShell脚本删除CSV文件的列和最后一行

时间:2019-02-12 10:21:01

标签: powershell csv

我有一个CSV文件,如下所示,但删除了ID,例如第1列和第4列,并删除了最后一行,并删除了语音标记,然后将新文件导出到UNC路径。我也希望脚本也尽可能从UNC路径运行。 加上_new后,新文件名是否可以与原始文件名相同?

当前文件(file.txt):

"col1","col2","col3","col4","col5"
"col1","col2","col3","col4","col5"
"col1","col2","col3","col4","col5"
"col1","col2","col3","col4","col5"
"","","","","","","","","","","","","1111.00","11",""

预期的最终结果(file_new.csv):

col2,col3,col5
col2,col3,col5
col2,col3,col5
col2,col3,col5

我尝试使用的PowerShell脚本是:

Import-Csv C:\temp\*.txt -Delimiter "," |
    Select Column2,Column3,Column5 |
    Export-Csv C:\Temp\New.txt -Delimiter "," -Encoding UTF8 -NoTypeInfo

1 个答案:

答案 0 :(得分:3)

由于您的文件没有标题(或它们被命名为col1..5),因此您必须提供它们

> Import-Csv file.txt -Header (1..5|%{"Column$_"}) |Select-Object Column2,Column3,Column5 -SkipLast 1

Column2 Column3 Column5
------- ------- -------
col2    col3    col5
col2    col3    col5
col2    col3    col5
col2    col3    col5

或使用专有名称:

> Import-Csv file.txt |Select-Object Col2,Col3,Col5 -SkipLast 1

col2 col3 col5
---- ---- ----
col2 col3 col5
col2 col3 col5
col2 col3 col5