Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace the first line of text from a file

Tags:

powershell

I would like to copy a file from one location to another, and replace the first line of text with a string. I almost have the script complete, 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
like image 537
BrokeMyLegBiking Avatar asked Sep 14 '10 12:09

BrokeMyLegBiking


People also ask

How do you change the first line of a text file in Python?

Use file. readlines() to edit a specific line in text file Use open(file, mode) with file as the pathname of the file and mode as "r" to open the file for reading. Call file. readlines() to get a list containing each line in the opened file . Use list indexing to edit the line at a certain line number.

How do you get the first line from a file using just the terminal?

To look at the first few lines of a file, type head filename, where filename is the name of the file you want to look at, and then press <Enter>. By default, head shows you the first 10 lines of a file. You can change this by typing head -number filename, where number is the number of lines you want to see.

Which is the correct command to replace the first occurrence?

By default, the sed command replaces the first occurrence of the pattern in each line and it won't replace the second, third…occurrence in the line.


1 Answers

Not a one-liner but it works (replace test1.txt and test2.txt with your paths):

.{
    "<text to add>"
    Get-Content test1.txt | Select-Object -Skip 1
} |
Set-Content test2.txt
like image 147
Roman Kuzmin Avatar answered Sep 21 '22 15:09

Roman Kuzmin