Reverse word order in text file

Welcome Forums General PowerShell Q&A Reverse word order in text file

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

 
Participant
2 years, 4 months ago.

  • Author
    Posts
  • #45922

    Participant
    Points: 0
    Rank: Member

    Hi

    I was given text file with list of employees in format lastname firstname and I want to reverse it. I tried this but nothing happens:

    (Get-Content -Path d:\employees.txt) | ForEach-Object -Process {
          $PSItem -replace "(\w+)\s(\w+)",'$2 $1'
    } | Set-Content -Path d:\employees.txt

    I guess syntax is an issue since

    "donner michael" -replace "(\w+)\s(\w+)",'$2 $1'

    works.

  • #45946

    Participant
    Points: 21
    Rank: Member

    I'm really bad at regex.

    ('dan potter'.split(' '))[1,0] -join ' '

  • #45953

    Participant
    Points: 21
    Rank: Member

    Here's another method.

    $a = 'dan potter'.split(' ')
    [array]::Reverse($a)
    $a -join ' '

    Or

    $a = 'dan potter'.split(' ')
    $a[$a.count..0] -join ' '

  • #45973

    Participant
    Points: 10
    Rank: Member
    $names = Get-Content -Path d:\employees.txt
    $results = foreach ($name in $names){$name -replace '(\w+) (\w+)','$2 $1'}
    $results | Out-File d:\results.txt
    

The topic ‘Reverse word order in text file’ is closed to new replies.