Read first line and then delete it

Hi, what would best way to to this kinda thing. I want to read txt files first line and save it to $ so I can use it later. After it had been read and saved it needs to be deleted.

At the moment I have done it like this and wondering how to delete row after this.

$Name = Get-Content -Path "$ScriptPath\rg.txt" | Select-Object -First 1

The easiest way would be to read the rest of the file and overwrite the original with it.

$Content = Get-Content -Path “$ScriptPath\rg.txt”
$FirstRow = $Content | Select-Object -First 1
$EveryThingExceptFirstRow = $Content | Select-Object -Skip 1
$EveryThingExceptFirstRow | Out-File -FilePath “$ScriptPath\rg.txt”

I assume that you have a bunch of text files and you are iterating through each file and its content, wraping the above reply for bunch of files

Get-ChildItem -Path c:\SomePath | ForEach-Object -Process {
    $YourContent = Get-Content -Path $_.FullName
    $YourVariable = $YourContent | Select-Object -First 1
    $YourContent | Select-Object -Skip 1 | Set-Content -Path $_.FullName

What it does,

  • Read the file
<li>Change what you want</li>

<li>Update remove/update what you need</li>

<li>Save it</li>

Here’s a one liner for deleting the first line.

set-content file.txt (get-content file.txt | select -skip 1)

Here’s another approach. That should really be $a.count-1 but it works anyway.

$a = get-content file.txt
$save = $a[0]
set-content file.txt $a[1..$a.count]

Learn something every day. I’ve never noticed the skip or skiplast parameters of select-object. Very cool, and definitely the better answer to his needs.

I personally would have done something more programatic like…
$var = Get-Content test.txt
$var = $var[1…$var.length]

I’d have expected that the $var.length needed to be placed in parenthesis, but at least in my console it didn’t.

Hey, thanks you for the answers!