Change files extension in a directory
June 22, 2023
A onliner
for f in *.old; do mv "$f" "${f%.old}.new"; done
How???
To change the name of a file on Linux/Unix use the mv
command
mv currentfilename newfilename
If there is a file named aleemisiaka.old
and want to rename to aleemisiaka.new
We can store the filename to a variable with export FILENAME=aleemisiaka
And use the variable name in the mv command
mv "$FILENAME"$ "$FILENAME.new"
This renames the file from aleem-isiaka.old to aleemisiaka.old.new
To ensure we end up with aleemisiaka.new
and not aleemisiaka.old.new we could use parameter expansion.
echo "${FILENAME%.old}"
would give just aleemisiaka
without the old.
Now append the new extension with echo "${FILENAME%.old}.new"
which gives aleemisiaka.new
Awesome
Back to mv
command
mv "$FILENAME}" "${FILENAME.old}.new"
Renames the file from aleemisiaka.old
to aleemisiaka.new
.
To replace all files in a directory use the Bash for loop
for f in *.old # Loops through all the files with the .old extensiondomv "$f" "${f%.old}.new" # renames from file.old to file.newdone# a onelinerfor f in *.old; do mv "$f" "${f%.old}.new"; done
Au revoir
Edit on githubTweet