Reverse word order in text file

This topic contains 3 replies, has 3 voices, and was last updated by Profile photo of random commandline random commandline 2 months, 3 weeks ago.

Viewing 4 posts - 1 through 4 (of 4 total)
  • Author
    Posts
  • #45922
    Profile photo of Bojan Zivkovic
    Bojan Zivkovic
    Participant

    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
    Profile photo of Dan Potter
    Dan Potter
    Participant

    I'm really bad at regex.

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

    #45953
    Profile photo of Dan Potter
    Dan Potter
    Participant

    Here's another method.

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

    Or

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

    #45973
    Profile photo of random commandline
    random commandline
    Participant
    $names = Get-Content -Path d:\employees.txt
    $results = foreach ($name in $names){$name -replace '(\w+) (\w+)','$2 $1'}
    $results | Out-File d:\results.txt
    
Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.