Welcome Forums General PowerShell Q&A Looking for awk equivalent

  • This topic has 2 replies, 3 voices, and was last updated 7 months ago by
Viewing 2 reply threads
  • Author
    • #167575
      Topics: 1
      Replies: 0
      Points: -4
      Rank: Member

      Unix admin here. I need to rename a bunch (thousands) of files on a windows server. As an example, the files need to go from a filename of backup-moodle2-course-33579-wi19_sosc235-01-20190127-2236.mbz to wi19_sosc2352236.mbz. I can accomplish this by moving the files to one of my unix servers and doing the following:

      for i in `ls`; do mv $i `ls $i|awk -F ‘-‘ ‘{x=$5$6; print x”.mbz”}’`; done

      This is not going to be a one time thing, so if I could create a script, or command line the user could run from Powershell on his own that would be great. I’m really new to Powershell (just heard about it today) and have been going through some documentation, but a little confused. So, if anyone has any ideas it would be greatly appreciated. Thanks.

    • #167632
      Senior Moderator
      Topics: 8
      Replies: 1164
      Points: 4,076
      Helping Hand
      Rank: Community Hero

      if it is to rename, you can use Rename-Item cmdlet. A small example below using delay binding and split.

      Get-ChildItem -Path $Path_To_The_Files -File | Rename-Item -WhatIf -NewName {
          $Split = $_.Name -split '-'
          $Split[4] + $Split[-1]

      PS: remove -WhatIf to actually do the operation.

    • #167650
      Topics: 28
      Replies: 752
      Points: 2,104
      Helping Hand
      Rank: Community Hero

      Wouldn’t that be x=$5$8 to get wi19_sosc2352236.mbz? Plus $8 would include .mbz already, so you wouldn’t need it a second time.

      Slight variation. Parameters that can be piped to, can use scriptblocks.

      Get-ChildItem | Rename-Item -NewName { $S = $_.basename -split '-'; $S[4] + $S[7] + '.mbz' } -whatif


      # these aliases were taken out of linux and osx to avoid confusion
      # I put them back in my $profile in osx
      set-alias ls get-childitem
      set-alias mv move-item
      foreach ($i in ls) { $s = $i -split '-'; mv $i ($s[4] + $s[7]) -whatif }
      foreach ($i in ls) { mv $i (-join ($i -split '-')[4,7]) -whatif }

      Here’s a simple demo of something like that awk operation:

      $a,$b,$c = 'one-two-three' -split '-'

      Basically the -split operator creates an array based on the delimiter, and then there are various ways to print the results.

      Just get Windows Powershell In Action.

Viewing 2 reply threads
  • The topic ‘Looking for awk equivalent’ is closed to new replies.