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
4 months, 3 weeks ago.

  • Author
    Posts
  • #118477

    Participant
    Points: 53
    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: 1,166
    Helping Hand
    Rank: Community Hero

    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: 1,628
    Helping Hand
    Rank: Community Hero

    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: 743
    Helping Hand
    Rank: Major 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: 53
    Rank: Member

    Hey, thanks you for the answers!

The topic ‘Read first line and then delete it’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort