How to rename files by removing a number and a fixed string from begin and keep just number before file extension?

  • 8 months ago
Comment

ChatGPT
1 / 1

You can achieve this using various scripting languages such as Python, PowerShell, or even a Windows batch script. Below are examples of how to accomplish this task using Python and PowerShell:

Using Python:

python
import os

def rename_files(directory):
for filename in os.listdir(directory):
if filename.endswith('.txt'): # Change to the desired file extension
new_filename = filename.split('_')[0] + os.path.splitext(filename)[1]
os.rename(os.path.join(directory, filename), os.path.join(directory, new_filename))

if __name__ == "__main__":
target_directory = "path_to_directory" # Replace with the actual directory path
rename_files(target_directory)

Using PowerShell:

powershell
$targetDirectory = "path_to_directory" # Replace with the actual directory path
$files = Get-ChildItem -Path $targetDirectory -Filter "*_*.txt" # Change the filter as needed

foreach ($file in $files) {
$newName = $file.Name -replace '_.*', $file.Extension
Rename-Item -Path $file.FullName -NewName $newName
}

Replace "path_to_directory" with the actual path of the directory containing the files you want to rename. Adjust the file extension and the separator (_ in this case) in the script according to your specific requirements.

Remember to test these scripts on a small set of files before using them on a large number of files to avoid unintended changes.