Author Posts

July 6, 2016 at 7:01 am

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.

July 6, 2016 at 11:31 am

I'm really bad at regex.

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

July 6, 2016 at 11:54 am

Here's another method.

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

Or

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

July 6, 2016 at 1:41 pm

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