Home > Blockchain >  Rename part of the directory names?
Rename part of the directory names?

Time:06-03

The following command found the following directories.

$ find tmp/ -name "date=*" -type d
tmp/year=2022/month=05/date=27
tmp/year=2022/month=05/date=21
tmp/year=2022/month=05/date=29
tmp/year=2022/month=05/date=24
tmp/year=2022/month=05/date=31
tmp/year=2022/month=06/date=01
tmp/year=2022/month=06/date=02

I need to rename the directories by replacing date= to day=.

find tmp/ -name "date=*" -type d -exec rename s/date=/day=/g "{}"  ;

However, the command doesn't rename the directories?

I will need to implement it in Python.

CodePudding user response:

rename utility is not part of standard Unix tool/utilities and comes in different flavors.

I may suggest sticking with bash and mv using this find command:

find tmp -name "date=*" -type d -exec bash -c '
   for f;do echo mv "$f" "${f/date=/day=}"; done' _ {}  

I have kept echo before mv for your testing purpose. Once satisfied with the output just remove echo from above command.

CodePudding user response:

If you want to do this from Python anyway, a subprocess is just unnecessary.

import os

for curdir, dirs, files in os.walk("/tmp"):
    for dirname in dirs:
        if dirname.startswith("date="):
            new = dirname.replace("date=", "day=")
            os.rename(os.path.join(curdir, dirname), os.path.join(curdir, new))

CodePudding user response:

If you are on Python 3.4 , you can use pathlib:

from pathlib import Path

tmp = Path('tmp')

for o in tmp.rglob('date=*'):
    if o.is_dir():
        o.rename(o.parent / o.name.replace('date', 'day'))
  • Related