PowerShell: How to Add Text to Specific Line in a File


You can use the following syntax in PowerShell to add text to a specific line in a file:

$my_file = Get-Content cities.txt
$my_file[6] += " is awesome"
$my_file | Set-Content cities.txt

This particular example will add the text “ is awesome” to the end of the line in index position 6 of the file named cities.txt.

Note that we used the Get-Content cmdlet to first return each line in the cities.txt file.

Then, we used += to add text to the end of the existing text in the line in a specific index position.

Lastly, we used Set-Content to save these changes to the existing cities.txt file.

The following example shows how to use this syntax in practice.

Example: How to Add Text to Specific Line in File Using PowerShell

Suppose we have a file named cities.txt in our current directory that contains the names of various U.S. cities.

We can use the Get-Content cmdlet to view the contents of this file:

Suppose that we would like to add the text “ is awesome” to the end of line 7 in the file.

We can use the following syntax to do so:

$my_file = Get-Content cities.txt
$my_file[6] += " is awesome"
$my_file | Set-Content cities.txt

The following screenshot shows how to use this syntax in practice:

PowerShell add text to specific line of file

Notice that when we use the Get-Content cmdlet again to view the updated contents of the cities.txt file we can see that the text ” is awesome” has been added to line 7 of the file.

All other lines in the file have remained unchanged.

Note: You can find the complete documentation for the Set-Content cmdlet in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Add Text to Each Line in a File
PowerShell: How to Use Export-Csv with Append
PowerShell: How to Count Number of Lines in File

Leave a Reply