Skip to content
Sign upLog in
← Back to Community

How to change the file extension for every file in the current directory and more!

Profile icon
DaRubyMiner360

Have you ever needed to change the file extension for every file in the current directory but didn't want to have to manually do it for every file? Well, ask no more!

Bash:

Rename File With Extension:

for file in *.old; do mv "$file" "$(basename "$file" .old).new" done

Delete File With Extension:

for file in *.old; do rm "$file" done

Replace All Occurrences In Files With Extension:

for file in *.old; do sed -i 's/replaceMe/replaceWith/g' $file done

Replace All Occurrences In All Files:

for file in *.*; do sed -i 's/replaceMe/replaceWith/g' $file done

Python:

Rename File With Extension:

import os, sys for filename in os.listdir(): if not os.path.isfile(filename): continue newname = filename.replace('.old', '.new') os.rename(filename, newname)

Delete File With Extension:

import os, sys for filename in os.listdir(): if not os.path.isfile(filename): continue if not filename.endswith(".old"): continue os.remove(filename)

Replace All Occurrences In Files With Extension:

import os, sys for filename in os.listdir(): if not os.path.isfile(filename): continue if not filename.endswith(".old"): continue f = open(filename, "r") contents = f.read() f.close() contents = contents.replace("replaceMe", "replaceWith") f = open(filename, "w") f.write(contents)

Replace All Occurrences In All Files:

import os, sys for filename in os.listdir(): if not os.path.isfile(filename): continue f = open(filename, "r") contents = f.read() f.close() contents = contents.replace("replaceMe", "replaceWith") f = open(filename, "w") f.write(contents)

In all of these, replace .old and .new with the file extensions of your choice, and with the replace all occurrences of replaceMe with replaceWith in all files with .old file extension, replace replaceMe and replaceWith with the text of your choice

Voters
Profile icon
RobertSoncrant
Profile icon
whattocode
Profile icon
EpicGamer007
Profile icon
DaRubyMiner360