patternbashMinor
Bash script to batch rename files
Viewed 0 times
scriptbatchfilesbashrename
Problem
This is my homebrew bash script for batch renaming files extensions (my music library needs organizing):
It works beautifully with my music files, but is this code sufficient or can I still improve on it? Also I've seen examples using
#!/bin/bash
# rext.sh
# Syntax: rext.sh EXT1 EXT2
# Batch rename any file in current directory with extension of EXT1 to EXT2
EXT1=$1
EXT2=$2
for f in *.$EXT1
do
fname=${f%.*}
newfname="$fname.$EXT2"
mv -v -i "$f" "$newfname"
doneIt works beautifully with my music files, but is this code sufficient or can I still improve on it? Also I've seen examples using
rename instead of mv, so is there any advantage in using rename?Solution
A tiny mistake is not quoting
If it contains a space, the script won't work as expected.
I agree it's an unrealistic corner case,
but it's easy enough to protect against with proper quoting:
The
Since you asked about its advantages:
The equivalent usage to simulate the behavior of your script would be:
A feature I like is the
$EXT1 in for f in *.$EXT1.If it contains a space, the script won't work as expected.
I agree it's an unrealistic corner case,
but it's easy enough to protect against with proper quoting:
for f in *."$EXT1".The
rename Perl script is famous for this purpose.Since you asked about its advantages:
- Stood the test of time
- You don't have to write it
- It has more features (full regex support)
The equivalent usage to simulate the behavior of your script would be:
rename -v 's/EXT1$/EXT2/' *.EXT1A feature I like is the
-n flag for dry run, to verify the renames that would be performed before actually performing them.Code Snippets
rename -v 's/EXT1$/EXT2/' *.EXT1Context
StackExchange Code Review Q#163186, answer score: 6
Revisions (0)
No revisions yet.