Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I efficiently pre-pend a line to a large file in Powershell

Tags:

powershell

I have some large files in CSV format that I would like to turn into objects using the Import-Csv command in Powershell. The files are missing the column headings however and these need to be added before I use Import-Csv. What is the fastest and most efficient way of adding these to the file?

like image 416
John Channing Avatar asked Mar 18 '09 22:03

John Channing


2 Answers

Prepending to a large file is not an easy or quick operation.

However, import-csv does have a "header" argument that you can use to specify the column headers, i.e.:

$header = 'Foo', 'Bar', 'Baz'
import-csv .\myfile.csv -header $header
like image 62
Michael Avatar answered Oct 01 '22 10:10

Michael


This one liner works nicely.

 @("Header Text") + (get-content myFile.txt) | set-content myFile.txt

Explanation

  • @("Header Text") creates an array with one item.
  • + (get-content myFile.txt) creates a new array with the contents of both.
  • | set-content myFile.txt pipes the result to set-content and saves to file.
like image 28
Shaun Luttin Avatar answered Oct 01 '22 10:10

Shaun Luttin