1

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.

0

1 Answer 1

5

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
10
  • 1
    Thanks for suggestion, i added it to my answer
    – protob
    Feb 24 at 10:43
  • #!/bin/bash for dir in ??????/ do dir=${dir%/} new_dir="20${dir:0:2}-${dir:2:2}-${dir:4:2}" mv "$dir" "$new_dir" done Is ok but we have another issue to come by if another file was created let's say 230104 it will be moved to the new directory which is already available 2023-01-04 mv "$dir" "$new_dir" No idea how to solve this issue Feb 24 at 18:16
  • What do you want to do with it then? Overwrite it? You can check if the directory already exists and use rm -rf to remove it if so.
    – protob
    Feb 24 at 18:45
  • 1
    I added the condition to the answer: if the dir already exists, it should move all contents to the existing one and delete the empty dir afterwards. if the dir doesn't exists, it should rename it.
    – protob
    Feb 24 at 20:32
  • 1
    More than enough, thank you very much. Feb 24 at 21:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.