I use OneDriveFB on Macs and somewhere there was a glitch where it added the file extension to the file name on a ton of files. I need help with a script to remove .pdf .jpeg .doc or any other extension and any spaces at the end or beginning of the file name if its part of the file name. Ideas on how to do this?
I'm a little confused. Generally speaking, almost all files have some type of file extension on them, even if it's normally hidden in the Finder. Are you sure these are extra extensions on top of what was there, or was it that it just made the extensions visible in Finder?
If I'm misunderstanding the issue here, can you post an example of a file that you think was affected by this that needs to be fixed?
I think you have "Show All Filename Extensions" in Finder Preferences > Advanced checked. Removing File Types .xxx name removes it's association with what program the OS is told to open it.
Do you have a situation where you have files with names like this:
file1.txt.txt
file2.jpg.jpg
file3.png.png
And you want to convert them in masse to this:
file1.txt
file2.jpg
file3.png
????
@ryan.ball Yes.
Might be able to make a sh file to check filenames & remove the dupe like
.jpg.jpg = .jpg
.pdf.pdf = .pdf
etc...
But I'm not sure where to start on that. Doing it by hand would be a PitA.
Ok. Hmm. Are these files with duplicate extensions all in one place, like all on the Desktop, or can they be and are they anywhere? Do you need to run this in an automated fashion across a bunch of Macs, or is this isolated to only a small number of devices that you can run a local script on to fix?
it's anywhere in the users home folder. Yes, it needs to be automated.
Something like this:
#!/bin/bash
directory="/your/directory/here"
while read -r file; do
if [[ $file =~ (.+).[^.]+.([^.]+)$ ]]; then
mv "$file" "${file%.*.*}.${file##*.}"
fi
done <<< "$(find "$directory" -depth 1)"
exit 0
Obviously try this on a test directory first.
@ryan.ball There's an issue with your script. It's only looking to see if the file has more than one period in it, and assuming that it's a duplicate file extension if there is. That's not a safe assumption to make. If I have a file called "My.Great.File.txt" that isn't a duplicate extension. The OS doesn't stop us from naming files with periods in them, so it's totally possible to run across files like that.
Using your script it would rename my file above to My.Great.txt
That is true. You'd probably want something to not only check to see if a file has more than one extension but also verify that both extensions are the same and write to a log the changes that it would be making.
This is a simple example and could be used as a baseline for something more thorough. This would be a good opportunity for someone to learn how to write a script as well.
Reply
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.