简体   繁体   中英

Batch Removing File Extensions OSX

i've got a folder with a lot of (~60,000) files in it. Most of them have the extension ".html.tmp" and I need to remove the ".tmp" part in all of them. I found some similar solutions but none worked exactly liked this. I also have only basic knowledge of the UNIX shell. OSX does not provide the "rename"-command. I guess a shell solution would be the most convenient but any other is welcome as well.

Thanks in advance. merriam

Use a loop to iterate over the output of Daniel's call to find ; it should be faster, as you'll cut down on the number of separate process that need to be created:

# Instead of calling sh, dirname, and basename for every file, use
# builtin bash commands to process the file name.
find /path/to/your/files -name '*.html.tmp' | while read fname; do
    mv "$fname" "${fname%.tmp}"
done

This should do what you want:

find /path/to/your/files -name '*.html.tmp' -exec sh -c 'mv -i "{}" "$(dirname "{}")/$(basename "{}" .tmp)"' \;

It looks a bit complicated because the simple solutions break if the filenames contain spaces or other shell metacharacters. I've used mv -i , so it should ask you before overwriting any files. I'd recommend you make a backup before trying this on your data.

The simplest solution looks like this:

for f in *.html.tmp; do mv "$f" "${f%.tmp}"; done

This does handle spaces correctly, and it doesn't require invoking a separate shell for every single file to rename (as Daniel's answer does), so it should be faster.


Your question states that your folder has ~60k files in it, suggesting that there are no nested subfolders that need processing. But if you find yourself in this same position but needing to recursively handle subfolders, then read on.

If you're using Bash 4.x and you're willing to turn on a shell option, then you can use the following:

shopt -s globstar
for f in **/*.html.tmp; do mv "$f" "${f%.tmp}"; done

The construct **/*.html.tmp with the globstar option set means match *.html.tmp not just in the current directory, but also in any subdirectories, recursively.

If your version of Bash is older than 4.x, then I would recommend using chepner's solution for recursive handling. But when you don't need recursion at all, my initial answer is the simplest.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM