How to Remove the Last Line from a File Using PowerShell?

As a PowerShell expert, I was required to remove the last line from a text file using PowerShell. There are different methods to achieve this. In this tutorial, I will explain various methods to remove the last line from a file using PowerShell.

For all the examples below, I will take a text file and the content of this text file is:

# New York
# Los Angeles
# Chicago
# Houston
# Phoenix

I then saved the text file in the Downloads folder on the macOS system. You can provide the file path according to where you saved the file.

Now we will see different methods with examples.

Method 1: Using Get-Content and Set-Content

The best way to remove the last line from a file is by using the Get-Content and Set-Content cmdlets in PowerShell. Here’s how you can do it:

$file = "/Users/bijay/Downloads/SampleFile.txt"
$content = Get-Content $file
$newContent = $content[0..($content.Length-2)]
$newContent | Set-Content $file

Let’s break down what’s happening in this script:

  1. We store the file path in the $file variable.
  2. We use Get-Content to read the contents of the file into the $content variable.
  3. We create a new array, $newContent, by taking all elements from $content except for the last one. We use the index range 0..($content.Length-2) to achieve this.
  4. Finally, we use Set-Content to overwrite the original file with the contents of $newContent.

This method is simple and works well for small to medium-sized files. However, for larger files, it may not be the most efficient approach.

I executed the above PowerShell script in my local system and you can see the exact output in the screenshot below:

Remove the Last Line from a File Using PowerShell

Check out Remove the Last Empty Line from a File Using PowerShell

Method 2: Using the -SkipLast Parameter

Now, let me show you another method.

Starting with PowerShell version 5, the Select-Object cmdlet gained a new parameter called -SkipLast. This parameter allows you to skip a specified number of objects from the end of the pipeline. Here’s how you can use it to remove the last line from a file:

$file = "/Users/bijay/Downloads/SampleFile.txt"
Get-Content $file | Select-Object -SkipLast 1 | Set-Content $file

In this one-liner, we:

  1. Read the contents of the file using Get-Content.
  2. Pipe the contents to Select-Object and use the -SkipLast 1 parameter to exclude the last line.
  3. Use Set-Content to overwrite the original file with the modified content.

This method is more concise and efficient than the previous one, especially for larger files. However, it requires PowerShell version 5 or later.

After I executed the above PowerShell script, you can see that the last line was removed using PowerShell. Check out the screenshot below:

PowerShell Remove the Last Line from a File

Read Create a File with Date in the Name Using PowerShell

Method 3: Using Regular Expressions

If you need more flexibility in identifying and removing the last line, you can use regular expressions with the -replace operator. This method is particularly useful when the last line has a specific pattern or content. Here’s an example:

$file = "/Users/bijay/Downloads/SampleFile.txt"
$pattern = "LastLinePattern"
(Get-Content $file) -replace "(?s).*$pattern.*`r`n", "" | Set-Content $file

In this script:

  1. We store the file path in the $file variable and the pattern to match in the $pattern variable.
  2. We read the contents of the file using Get-Content and wrap it in parentheses to treat the entire content as a single string.
  3. We use the -replace operator with a regular expression to match the last line containing the specified pattern and replace it with an empty string.
    • The (?s) flag enables single-line mode, allowing the dot (.) to match newline characters.
    • .* matches any characters before and after the pattern.
    • $pattern is the variable containing the pattern to match.
    • .*\r`n` matches any remaining characters until the end of the line.
  4. Finally, we use Set-Content to overwrite the original file with the modified content.

This method offers more control over the last line removal process, allowing you to target specific patterns or content.

Handle Different Cases That Might Come

When removing the last line from a file, there are a few edge cases to consider:

  1. Empty files: If the file is empty, removing the last line will have no effect. You can add a check to ensure the file has content before proceeding with the removal.
  2. Single-line files: If the file contains only one line, removing the last line will result in an empty file. Depending on your requirements, you may want to handle this case differently.
  3. File permissions: Ensure you have the necessary permissions to read and write to the file. If you encounter access denied errors, double-check your file permissions.

Conclusion

In this tutorial, I explained how to use various methods to remove the last line from a file using PowerShell. You can use the simplicity of Get-Content and Set-Content, the efficiency of the -SkipLast parameter, or the flexibility of regular expressions.

I hope this tutorial has helped you through the process of removing the last line from a file using PowerShell.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.