Created
February 18, 2024 13:49
-
-
Save keithrbennett/82856df3a6e966a3188d9df1b6783ff7 to your computer and use it in GitHub Desktop.
Renames Mac screenshot files using a more command line friendly format.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# This script reads the filespecs in the current directory, collects names of files | |
# in the default screenshot file name format, converts the names to lower case | |
# with spaces converted to hyphens, and removes the "at" to produce a command line friendly filespec; | |
# for example, "Screenshot 2024-02-18 at 21.06.31.pdf" becomes "screenshot-2024-02-18--21.06.31.pdf". | |
# | |
# It ignores but preserves the extensions, so if you have changed the screenshot file type with, e.g.: | |
# defaults write com.apple.screencapture type pdf && killall SystemUIServer | |
# then it will rename those PDF files too. | |
# It defaults to searching the directory for all matching files, but you can also specify | |
# If "-n" is added to the command line then it shows the new names but does not rename the files. | |
import os | |
import sys | |
import re | |
def rename_files(dry_run=False, files=None): | |
pattern = re.compile(r'Screenshot \d{4}-\d{2}-\d{2} at \d{2}\.\d{2}\.\d{2}\.*') | |
if files is None: | |
files = os.listdir('.') | |
matching_files = filter(pattern.match, files) | |
for filename in matching_files: | |
new_name = compute_new_name(filename, pattern) | |
if not dry_run: | |
os.rename(filename, new_name) | |
def compute_new_name(filename, pattern): | |
name, extension = os.path.splitext(filename) | |
new_name = name.lower().replace(" ", "-").replace("at", "") + extension | |
print(f"Old Name: {filename} -> New Name: {new_name}") | |
return new_name | |
def main(): | |
dry_run = process_dry_run() | |
files = [arg for arg in sys.argv[1:]] | |
rename_files(dry_run, files if files else None) | |
def process_dry_run(): | |
dry_run = "-n" in sys.argv | |
if dry_run: | |
sys.argv.remove("-n") | |
print("Dry run mode; not changing file names.") | |
else: | |
print("Changing file names:") | |
return dry_run | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment