Friday, December 27, 2019

Trim characters from the end of all directory names in a folder

On my windows system, I had a folder with only other folders in it, and all of them had three characters on the ends of their names that I wanted to delete. I started up a Cygwin Bash shell to do the job.

I first attempted to use 'find' to create a one line command to rename all of these folders, but it turns out bash for and do were the answer, thusly:
for file in *; do mv "$file" "${file%???}"; done

The syntax for doing the trimming came from this thread (although sadly the pythonesqe method of trimming with colons and a negative end position didn't work in cygwin bash for some reason): https://stackoverflow.com/questions/19530429/rename-file-by-removing-last-n-characters
The example of using for/do came from here: https://stackoverflow.com/questions/7450818/rename-all-files-in-directory-from-filename-h-to-filename-half