Issue
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.
Solution
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.with_name(o.name.replace('date', 'day')))
To address the problem you mentioned in your post comment, you can check if the target directory already exists and then workaround it the way you want. Something like this:
from pathlib import Path
tmp = Path('tmp')
for o in tmp.rglob('date=*'):
new_name = o.with_name(o.name.replace('date', 'day'))
if o.is_dir():
if new_name.exists():
# Your logic to work around a directory
# that already exists goes here
else:
o.rename(new_name)
The code above is just an initial idea. It needs a lot of improvement to be made more reliable.
Answered By - accdias Answer Checked By - Pedro (WPSolving Volunteer)