Replace the first line of text from a file

I would like to copy a file from one place to another and replace the first line of text with a line. I almost finished the script, but not quite there. (See below)

# -- copy the ASCX file to the control templates $fileName = "LandingUserControl.ascx" $source = "D:\TfsProjects\LandingPage\" + $fileName $dest = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\CONTROLTEMPLATES\LandingPage" #copy-item $source $dest -Force # -- Replace first line with assembly name $destf = $dest + "\" + $fileName $destfTemp = $destf + ".temp" Get-Content $destf | select -skip 1 | "<text to add>" + $_) | Set-Content $destfTemp 
+4
source share
2 answers

Not one-line, but it works (replace test1.txt and test2.txt with your own paths):

 .{ "<text to add>" Get-Content test1.txt | Select-Object -Skip 1 } | Set-Content test2.txt 
+8
source

In "more than one way to flatten a cat," you can do the same with Out-File, if that's your preference on Thursdays. Written for a better understanding of flow compared to single line condensation.

 $x = Get-Content $source_file $x[0] = "stuff you want to put on first line" $x | Out-File $dest_file 

This takes advantage of the fact that Get-Content creates an array, with each row being an element of this array.

+5
source

All Articles