如何在 CSV 中移动列值并添加新值

电话

我必须使用 PowerShell 在我的 CSV 数据中创建一个新列。

有我的代码:

$csv = Import-Csv .\test1.csv -Delimiter ';'

$NewCSVObject = @()  
foreach ($item in $csv)  
{  
    $NewCSVObject += $item | Add-Member -name "ref" -value " " -MemberType NoteProperty  
}  
$NewCSVObject | export-csv -Path ".\test2.csv" -NoType

$csv | Export-CSV   -Path ".\test2.csv" -NoTypeInformation -Delimiter ";" -Append

当我打开文件时,该列在此处,但在右侧,我希望将其放在左侧,就像 A 列一样。我不知道是否可以像这样将两个对象在一行中导出(它没有)工作):

$csv,$NewCSVObject | Export-CSV   -Path ".\test2.csv" -NoTypeInformation -Delimiter ";" -Append

输入文件(它会有更多的行,而不仅仅是一行):

ABCDEFGH 
T-89 T-75 T-22 Y-23 Y-7 Y-71

当前输出文件:

ABCDEFGH 
Y-23 Y-7 Y-71 ref: ref2:

Excel表格中的预期结果,在产品列前显示“ref:”和“ref:2”:

ABCDEFGH 
ref: T-89 T-75 T-22 ref2: Y-23 Y-7 Y-71  
马特

如果我们只是将文件视为纯文本文件并将其保存为 csv 格式,这可能会更简单。可以使用 csv 对象并将值移动到其他行中,但这并不是必需的。您通过添加列的方法Add-Member无法实现此目标,因为它将添加新列并且与您想要的输出不匹配。Export-CSV想要写入具有相同属性的文件对象以及您正在混合的文件对象,这给了您意想不到的结果。

这是执行此操作的详细方法。您可以使用正则表达式之类的东西轻松缩短它(见下文)。我选择了这种方法,因为它更容易跟踪正在发生的事情。

# Equivelent to Get-Content $filepath. This just shows what I am doing and is a portable solution.
$fileContents = "A;B;C;D;E;F;G;H",
"T-89;T-75;T-22;Y-23;Y-7;Y-71",
"T-89;T-75;T-22;Y-23;Y-7;Y-71"

 $newFile = "C:\temp\csv.csv"

# Write the header to the output file.
$fileContents[0] | Set-Content $newFile 

# Process the rest of the lines. 
$fileContents | Select-Object -Skip 1 | ForEach-Object{
    # Split the line into its elements
    $splitLine = $_ -split ";"

    # Rejoin the elements. adding the ref strings
    (@("ref:") + $splitLine[0..2] + "ref2:" + $splitLine[3..5]) -join ";"
} | Add-Content $newFile 

最后一行是连接一个数组。以 "ref:" 开头,添加分割线的前 3 个元素,然后是 "ref2:" 和其余元素。该新数组以分号连接并通过管道发送到文件中。


如果您愿意尝试使用正则表达式,则可以使用更少的代码来完成。

$fileContents = Get-Content "C:\source\file\path.csv"
$newFile = "C:\new\file\path.csv"
$fileContents[0] | Set-Content $newFile
($fileContents | Select-Object -Skip 1) -replace "((?:.*?;){3})(.*)",'ref:;$1ref2:;$2' | Add-Content $newFile

这样做是将每一行拆分到第 3 个分号(Explanation的第一行之外替换字符串是根据引用字符串和匹配的内容构建的。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章