Skip to content

Instantly share code, notes, and snippets.

@kschlottmann
Last active February 28, 2024 18:28
Show Gist options
  • Save kschlottmann/1be8cea176145ea3b3ff09f5fb8893bb to your computer and use it in GitHub Desktop.
Save kschlottmann/1be8cea176145ea3b3ff09f5fb8893bb to your computer and use it in GitHub Desktop.
Powershell one-liners for cleaning up file and directory names
(Get-ChildItem -Recurse -File) |
Where-Object { $_.Name -match '[^a-zA-Z0-9.-]' } |
Rename-Item -NewName { $_.Name -replace '[^a-zA-Z0-9.-]+', '_' } -WhatIf
# As written, this will preview a list of changes where non-ASCII characters as described by the regex are replaced by an underscore
# Delete line 4 (-WhatIf) and re-run to actually make the changes
# To act on directories: in line 1, replace -File with -Directory, and replace regex with [^a-zA-Z0-9] so as to capture periods
# In lines 2 and 3, replace regex with any other character or regex that is desired, e.g. ' ' for replacing only spaces
#Be sure to use the correct regex for files and directories, because we do not want to rename hidden files starting with a period (e.g. .DS_store), because they are otherwise hard to find programatically
#Regex for directories: [^a-zA-Z0-9]
#Regex for files, which adds a period to the characters skipped: [^a-zA-Z0-9.]
#Larger regex allowing for more ASCII characters: [^\x20-\x81]
@kschlottmann
Copy link
Author

Use this Powershell grep command to find non-alphanumber and non-period or underscore characters:
dir -R | Select-String -Pattern "[^a-zA-Z0-9._]"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment