Search code examples
bashrenamemove

Add number 20 to folder names and (-) between sections


He guys I have folders listed as 230101 230102 230103 - infinite daily made I need a way in bash or batch to re name the folders to 2023-01-01 as example But I need it to be automated So the issue is we need to add number 20 In beginning of the folder name and two - to every folder Any suggestions?

I have tried to make the name of the files as variable I kept getting a lot of errors so I need someone to guide me please.


Solution

  • You can use the loop that creates new_dir names from sub-strings of dir names. The ??????/ glob is used to match only directories with 6-character names:

    #!/bin/bash
    
    for dir in ??????/; do
      dir=${dir%/}
      new_dir="20${dir:0:2}-${dir:2:2}-${dir:4:2}"
      if [ -d "$new_dir" ]; then
        mv -n "${dir}"/* "$new_dir"/
        rmdir "${dir}"
      else
        mv "$dir" "$new_dir"
      fi
    done