powershell regex delete white space before string

Welcome Forums General PowerShell Q&A powershell regex delete white space before string

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

 
Participant
5 months, 4 weeks ago.

  • Author
    Posts
  • #100744

    Participant
    Points: 1
    Rank: Member

    hello all,

    My initial goal was to retrieve a set of specific strings (virtual machine names) out of txt file.
    Because I wanted only the VM name, I used the -replace operator to remove the unnecessary string ("Display Name:") in a calculated property.
    Thus, my final command would be:
    get-content vm-process.txt | select-string "Display Name:" | Select @{l='VM Name'; e={$_.line -replace 'Display Name: ',' ' }} | sort -Property 'VM Name'

    Whilst my output (shown below) is the anticipated, I would like to polish it by eliminating this which space prior to each 'vmnumber'. Any ideas? if there is a "faster" way to do it is also welcome.

    VM Name
    -------
        vmnumber1
        vmnumber2
        vmnumber3
        vmnumber4
        vmnumber5
        vmnumber6
    
  • #100843
    js

    Participant
    Points: 202
    Helping Hand
    Rank: Participant

    \s* is any amount of whitespace. You can replace it with the empty string ". You can try out regex interactively at https://regex101.com.

    PS /Users/js> 'Display Name:     VM1' -replace 'Display Name:\s*',''                                                              
    
    VM1
    
  • #100851

    Participant
    Points: 134
    Helping Hand
    Rank: Participant

    You could use the .trimStart() – method to remove leading withespace ... if there is trailing withespace as well you could use the .trimEnd() – method. ... like this

    get-content vm-process.txt  |
        ForEach-Object {
            $_.trimStart().trimEnd()
        }
  • #100900

    Participant
    Points: 1
    Rank: Member

    thank you both

The topic ‘powershell regex delete white space before string’ is closed to new replies.