使用 powershell 在 csv 文件中添加列和操作现有列值

Adding columns and manipulating existing column values in csv file using powershell

我有很多 csv 文件,其值排列如下:

X1,Y1
X2,Y2
...,...
Xn,Yn

我发现用 excel 处理这些文件非常乏味,所以我想设置一个批处理脚本来处理这些文件,使它们看起来像这样:

#where N is a specified value like 65536
X1,N-Y1,1
X2,N-Y2,2
...,...,...
Xn,N-Yn,n

我最近才开始使用 powershell 进行图像处理(非常简单的脚本)和文件名附加,所以我不确定如何去做。我遇到的很多寻求回答这个问题的脚本都使用每列带有标题的 csv 文件,而我的文件只是第一行没有 object 标题的值数组。我想避免 运行 多个脚本来添加标题。

我的奖金问题是我还没有找到一个好的答案,并且是处理过程中最乏味的部分。使用 excels 排序函数,我通常更改 Col2 中 Yn 值的顺序,以便它们在导出的 csv 中排序,如下所示:

X1,N-Yn,n
...,...,...
Xn-1,N-Y2,2
Xn,N-Y1,1

使用 Col3 值作为排序顺序(从大到小),然后我删除此列,以便最终保存的 csv 仅包含前两列(关键步骤)。任何帮助都将不胜感激,对于这个问题的long-winded-ness,我深表歉意。

我会尝试类似的方法,通过使用计算table script-property 扩展原始 table 作为新列:

#Your N number
$N = 65536

# Import CSV file without header columns
$table = Import-Csv -Header @("colX","colY") `
    -Delimiter ',' `
    -Path './numbers.csv'

Write-Host "Original table"
$table | Format-Table

# Manipulate table
$newtable = $table |
Add-Member -MemberType ScriptProperty -Name colNX -Value { $N-$this.colX } - PassThru

Write-Host "New table"
$newtable | Format-Table

I have encountered looking to answer this question use csv files with titles per column whereas my files are just arrays of values without object titles in the first row.

Import-Csv-Header参数用于在文件不包含header列时添加它们。它需要一个字符串数组,不管有多少列。

I would like to avoid running multiple scripts to add titles.

如果不能使用-Header,可以将带有Get-Content的行读入内存,在内存中添加一个header,然后全部使用ConvertFrom-CSV在一个脚本中。

就是说,如果我没看错的话,你想要:

  • 输入文件中没有header,我想输出文件中没有header
  • 添加第三列并对其进行排序和删除的全部意义只是为了反转行?
  • 您保留的唯一一列是第 1 列?

我不会为此使用 Import-Csv,它不会使它变得更好。

$n = 65536

# Read lines into a list, and reverse it
$lines = [Collections.Generic.List[String]](Get-Content -LiteralPath 'c:\test\test.csv')
$lines.Reverse()


# Split each line into two, create a new line with X and N-Y
# write new lines to an output file
$lines | ForEach-Object {

    $x, $y = $_.split(',')

    "$x,$($n - [int]$y)"

} | Set-Content -LiteralPath 'c:\test\output.csv' -Encoding Ascii

如果您确实想使用 CSV 处理,那么:

$n = 65536
$counter = 1
Import-Csv -LiteralPath 'C:\test\test.csv' -Header 'ColX', 'ColY' |
    Add-Member -MemberType ScriptProperty -Name 'ColN-Y' -Value {$n - $_.ColY} -PassThru |
    Add-Member -MemberType ScriptProperty -Name 'N' -Value {$script:counter++} -PassThru |
    Sort-Object -Property 'N' -Descending |
    Select-Object -Property 'ColX', 'ColN-Y' |
    Export-Csv -LiteralPath 'c:\test\output.csv' -NoTypeInformation

但输出将包含 CSV headers 和 double-quoted 值。