PIPRON79
PIPRON79

Reputation: 141

powershell incremental lines in csv

I have a csv journal file like this: enter image description here

and I would like to add incremental line numbering like the below: enter image description here

Can anyone suggest the easiest way to do this through PowerShell so that every time a file is generated it will automatically insert a column called LINENUMBER and insert the incremental numbering?

All help greatly appreciated.

Upvotes: 1

Views: 1224

Answers (1)

Mark Wragg
Mark Wragg

Reputation: 23355

You could do this:

Import-CSV SomeFile.csv | Select *,LINENUMBER | ForEach-Object -Begin { $Line = 1 } { 
    $_.LineNumber = $Line++
    $_ 
} | Export-CSV SomeFile.csv
  • Uses Import-CSV to load the CSV file as a PowerShell object and then Select-Object to return all of it's properties and add an additional property named 'LINENUMBER'
  • Iterates through each line of the CSV, incrementing the new LINENUMBER property with a counter variable named $Line (which is set to 1 before it iterates).
  • Exports the result as CSV overwriting the original (or you could here redirect it to a new file name).

Note that the new column will be last. You could make it the first column by changing the Select part to Select LINENUMBER,*. If you want it to sit somewhere in the middle that would be slightly more complicated (and likely involve knowing what headers the input file had in advance).

Upvotes: 2

Related Questions