Reputation: 141
I have a csv journal file like this:
and I would like to add incremental line numbering like the below:
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
Reputation: 23355
You could do this:
Import-CSV SomeFile.csv | Select *,LINENUMBER | ForEach-Object -Begin { $Line = 1 } {
$_.LineNumber = $Line++
$_
} | Export-CSV SomeFile.csv
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'$Line
(which is set to 1 before it iterates).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