[英]Using powershell to transform CSV file
I have CSV files which have a lot of columns. 我有CSV文件,有很多列。 I need to transform several columns, for example, some date columns have text string of "Missing" and I want to replace "Missing" to an empty string, etc.
我需要转换几个列,例如,某些日期列的文本字符串为“Missing”,我想将“Missing”替换为空字符串等。
The following code may work but it will be a long file since there are a lot of columns. 以下代码可能有效,但由于有很多列,因此它将是一个长文件。 Is it a better way to write it?
这是一个更好的写作方式吗?
Import-Csv $file |
select @(
@{l="xxx"; e={ ....}},
# repeat many times for each column....
) | export-Csv
You could use an imperative style rather than a pipelined style: 您可以使用命令式样式而不是流水线样式:
$records = Import-Csv $file
foreach ($record in $records)
{
if ($record.Date -eq 'Missing')
{
$record.Date = ''
}
}
$records | Export-Csv $file
Edit: To use a pipelined style, you could do it like this: 编辑:要使用流水线样式,您可以这样做:
import-csv $file |
select -ExcludeProperty Name1,Name2 -Property *,@{n='Name1'; e={"..."}},@{n='Name2'; e={'...'}}
The *
is a wildcard that matches all properties. *
是匹配所有属性的通配符。 I couldn't find a way to format this code in a nicer way, so it is kind of ugly looking. 我找不到以更好的方式格式化这段代码的方法,所以它看起来很难看。
If all you want to do is a find-replace, you don't really need to read it as a CSV. 如果您只想进行查找替换,则无需将其作为CSV读取。
You could do this instead: 你可以这样做:
Get-Content $file | %{$_.ToString().Replace("Missing", "")} | Out-File $file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.