#PSTip How to remove the first line from a text file

There are a lot of ways to remove the first line from a text file. I hope you will find a multiple assignment technique interesting. Here is what you need to do:

PS C:\> $a,$b = Get-Content .\test.txt
PS C:\> $b > .\test.txt

The first line of the test.txt file is asigned to the $a variable, the rest of the file goes to the variable $b, and then you write a content of the $b variable to the test.txt file by using > redirection operator.

But wait, there is more! You can turn that into a one-liner:

PS C:\> $a, ${c:test.txt} = Get-Content .\test.txt
Filed in: Columns, Tips and Tricks Tags: , , ,

7 Responses to "#PSTip How to remove the first line from a text file"

  1. sahal says:

    This is cool, never knew this

  2. Bob says:

    ${ filename} seems to have limitations. can you use this approach if the file path is held in a variable?

  3. Joe says:

    This is one of the coolest examples of code I have seen for PowerShell. Seriously, big grin on my face cool.

    Thanks for sharing!

  4. greg says:

    Thanks, this worked well, but I have a question. I’m using the 2 line version and I noticed the ‘new’ file with the first line stripped out is twice as big as the input file. I was testing with a small 20 line text file and the line gets stripped out and a file comparison using Notepad++ or Textpad both show the only difference is the missing line yet the output file is twice as large (14k vs 7k).

    Any idea why that is the case? This isn’t an issue with small text files, but I could see where this solution might not scale.

Leave a Reply

Submit Comment

© 2017 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: