Reputation: 2049
if I have some files with the name pippo_yyyymmdd.txt, pluto_yyyymmdd.txt etc etc, how can I remove the timestamp and rename the files as pippo.txt, pluto.txt ?
Upvotes: 1
Views: 7910
Reputation: 21
I was facing the same problem but unfortunately, PowerShell did not help me to solve it. So I then resorted to using Python to solve this problem and it worked like a bomb. You only need to copy the python script into the affected folder and run the script to remove the timestamp from all the files in the folder and subfolders.
import os, sys, re
fileNameList =[]
patho = os.path.dirname(os.path.realpath(sys.argv[0]))
def renamer(fpath):
for path, subdirs, files in os.walk(fpath):
for name in files:
if re.findall(r"(?ix)(\.ini)", name, re.I) == None:
if re.search(r"(?ix)(\(\d{4}\_\d{2}_\d{2}\s\d{2}\_\d{2}\_\d{2}\sutc\))", name, re.I) != None:
old_name = os.path.join(path,name)
print(old_name)
new_name = re.sub(r"(?ix)(\s\(\d{4}\_\d{2}_\d{2}\s\d{2}\_\d{2}\_\d{2}\sutc\))", "", old_name, re.I)
print(new_name)
try:
os.replace(old_name,new_name)
except:
print(old_name)
fileNameList.append(old_name)
def log_errors_directories(fileNameList):
filename = "Log of error filenames.txt"
if len(fileNameList) != 0:
log = open(filename, "a")
log.write("###########################################################\n")
i = 1
for line in fileNameList:
nr_line = str(i) + " " + str(line)
log.write(str(nr_line))
log.write("\n")
i += 1
log.write("###########################################################\n\n")
log.close()
renamer(patho)
log_errors_directories(fileNameList)
This is my first time posting code online. I hope it works for you as it did for me. :)
Upvotes: 2
Reputation: 126932
Give this a try, it will remove any underscore followed by 8 digits. This is tha basicmidea, it doesn't take care of files end up having the same name:
Get-ChildItem *.txt |
Where {$_.Name -match '_\d{8}\.txt' } |
Rename-Item -NewName {$_.Name -replace '_\d{8}'}
Upvotes: 5