Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用powershell重新格式化csv_Powershell - Fatal编程技术网

使用powershell重新格式化csv

使用powershell重新格式化csv,powershell,Powershell,我有一个包含很多行的文件,格式如下: firstname ; lastname ; age ; (有点复杂,但基本上就是这个文件) 因此字段是固定长度的,用空格填充,字段之间用分号填充 我希望如此: firstname, lastname, age, (逗号和无固定宽度) 我已经用regexp替换了逗号,但是我还想修剪字符串的结尾。但我不知道怎么做 以下是我的开始,但我无法在其中获得“.TrimEnd()”。我也曾想过尝试使用“-replace”(“,”),但我

我有一个包含很多行的文件,格式如下:

firstname     ; lastname     ; age     ;  
(有点复杂,但基本上就是这个文件)

因此字段是固定长度的,用空格填充,字段之间用分号填充

我希望如此:

firstname, lastname, age, 
(逗号和无固定宽度)

我已经用regexp替换了逗号,但是我还想修剪字符串的结尾。但我不知道怎么做

以下是我的开始,但我无法在其中获得“.TrimEnd()”。我也曾想过尝试使用“-replace”(“,”),但我无法将其集成到这个表达式中:

Get-Content .\Bestand.txt | %{$data= [regex]::split($_, ';'); [string]:: join(',', $data)}

我可以获得一些关于如何实现这一点的信息吗?

我建议您将每次出现的“space;space”替换为逗号(假设替换的字符不在有效值内),因此最终结果如下所示:

firstname,lastname,age
保持如下状态不是一个好主意,因为现在您的一些标题(属性名称)以空格开头:

"firstname, lastname, age,"
尝试一下(制作文件副本):


现在,使用
import-Csv
cmdlet导入和处理文件变得很容易。

既然您已经创建了Csv,我会一直创建正确的Csv:

$cols = "firstname","lastname","age","rest"

Import-Csv "C:\input.txt" -Delimiter ";" -Header $cols | % {
  foreach ($property in $_.PsObject.Properties) {
    $property.Value = ([string]$property.Value).Trim()
  }
  $_
} | Export-Csv "C:\output.csv" -NoTypeInformation

-replace
运算符采用正则表达式,可用于删除所有前导空格和尾随空格:

Get-Content .\Bestand.txt | 
    Foreach-Object { $_ -replace ' *; *',',' } |
    Out-File .\Bestand.csv -Encoding OEM

我建议在
的两侧使用任意数量的空格,方法是使用
$\u替换'\s*.\s*',','
,这也是有效的,我会使用+而不是*-替换还将数组(或管道输出)作为输入:
(cat.\bestand.txt)-替换“*;*”,“,”| Out文件。\Bestand.csv-编码OEM
有任意数量的空格,因此这是一种魅力。
Get-Content .\Bestand.txt | 
    Foreach-Object { $_ -replace ' *; *',',' } |
    Out-File .\Bestand.csv -Encoding OEM