Read first line and then delete it

Welcome Forums General PowerShell Q&A Read first line and then delete it

This topic contains 5 replies, has 5 voices, and was last updated by

 
Participant
1 month, 2 weeks ago.

  • Author
    Posts
  • #118477

    Participant
    Points: 28
    Rank: Member

    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
  • #118498

    Participant
    Points: 261
    Helping Hand
    Rank: Contributor

    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" 
  • #118518

    Participant
    Points: 866
    Helping Hand
    Rank: Major Contributor

    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
    • Change what you want
    • Update remove/update what you need
    • Save it
  • #118533
    js

    Participant
    Points: 318
    Helping Hand
    Rank: Contributor

    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]
    
  • #118591

    Participant
    Points: 9
    Rank: Member

    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.

  • #119607

    Participant
    Points: 28
    Rank: Member

    Hey, thanks you for the answers!

You must be logged in to reply to this topic.