用于从CSV中删除空白列的Powershell脚本

时间:2015-02-24 09:54:15

标签: mysql powershell csv

从CSV中删除空白列的Powershell脚本

我有一张电子表格,我将其导入MySQL数据库,由于电子表格中有空白列,导入失败。

我是否可以运行/创建一个powershell脚本来检查任何给定的CSV文件并删除空白列?

Col1中,Col2中,COL3,COL4 ,,,, VAL1,VAL2,VAL3,VAL4

2 个答案:

答案 0 :(得分:1)

这样的事情怎么样:

$x = Import-Csv YourFile.csv
$f = $x[0] | Get-Member -MemberType NoteProperty | Select name
$f | Add-Member -Name count -Type NoteProperty -Value 0
$f | %{
  $n = $_.Name
  $_.Count = @($x | Select $n -ExpandProperty $n | ? {$_ -ne ''}).count
}
$f = @($f | ? {$_.count -gt 0} | Select Name -expandproperty Name)

$x | Select $f | Export-Csv NewFile.csv -NoTypeInformation

它使用Get-Member获取列名,循环每个列以查看有多少不是空白,然后在选择中使用结果。

答案 1 :(得分:0)

当我运行Dave Sexton的代码时,我得到:

Select-Object : Cannot convert System.Management.Automation.PSObject to one of the following 
types {System.String, System.Management.Automation.ScriptBlock}.
At line:15 char:12
+ $x | Select <<<<  $f  | Export-Csv ColsRem.test.$time.csv -NoTypeInformation
+ CategoryInfo          : InvalidArgument: (:) [Select-Object], NotSupportedException
+ FullyQualifiedErrorId : 
                  DictionaryKeyUnknownType,Microsoft.PowerShell.Commands.SelectObjectCommand

我通过再添加一行来纠正这个问题,以强制每个数组元素为字符串。

$x = Import-Csv YourFile.csv
$f = $x[0] | Get-Member -MemberType NoteProperty | Select name
$f | Add-Member -Name count -Type NoteProperty -Value 0
$f | %{
  $n = $_.Name
  $_.Count = @($x | Select $n -ExpandProperty $n | ? {$_ -ne ''}).count
}
$f = @($f | ? {$_.count -gt 0} | Select Name -expandproperty Name)

# I could get the select to work with strings separated by commas, but the array would 
# always produce the error until I added the following line, explicitly changing the 
#values to strings.
$f = $f | Foreach-Object { "$_" } 

$x | Select $f | Export-Csv NewFile.csv -NoTypeInformation

我的导入CSV包含几百列,大约一半可能不会填充,因此必须删除额外的列。现在我只需要弄清楚如何在不改变名称的情况下,按字母顺序按字母顺序抵消列的意外重新排序。

相关问题