PowerShell: How to Remove First Line from a File


Often you may want to use PowerShell to remove the first line from a file.

You can use the following syntax to do so:

(Get-Content $my_file | Select-Object -Skip 1) | Set-Content $my_file

This particular example will remove the first line from the file specified by the path in the variable named $my_file.

Here is what the various commands do:

  • Get-Content: Retrieves all lines from the file
  • Select-Object -Skip 1: Selects all lines except the first line of the file
  • Set-Content: Sets the content of the file to be equal to all lines except the first line

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

Example: How to Remove First Line from a File Using PowerShell

Suppose we have a file named athletes.txt that contains information about various basketball players.

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

Now suppose that we would like remove the first line from this file.

We can use the following syntax to do so:

$my_file = "athletes.txt"
(Get-Content $my_file | Select-Object -Skip 1) | Set-Content $my_file 

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

PowerShell remove first line from file

Notice that when we use the Get-Content cmdlet again to view the updated contents of the athletes.txt file we can see that the first line has been removed from the file.

Note: You can find the complete documentation for the Select-Object cmdlet in PowerShell here.

Related Tutorials

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

PowerShell: How to Get the Last N Lines of a File
PowerShell: How to Count Number of Lines in File
PowerShell: How to Get Line Number of Matches

Leave a Reply