How can I batch rename files in bash?
Another option:
for i in *.sql ; do
mv -v $i ${i%.sql}-AM.sql
done
This loops through all the .sql files and renames them to end in -AM.sql instead.
PROTIP: Use $(command)
instead of `command`
in your scripts (and command-lines), it makes quoting and escaping less of a nightmare.
Try this little script:
#!/bin/sh
FILES=`ls *.sql`
for FILE in ${FILES}
{
BASE=`basename ${FILE} .sql`
mv ${FILE} ${BASE}-AM.sql
}
I just typed that from memory so if it doesn't work 100% don't blame me (i.e., back up your data first ;) )
How it works:
Collect all files into a variable (you could put this inside the for instead but I like to keep things easy to read):
FILES=`ls *.sql`
Loop through each file:
for FILE in ${FILES} { ... }
Get the filename without .sql:
BASE=`basename ${FILE} .sql`
Rename the file, adding -AM.sql to the base name:
mv ${FILE} ${BASE}-AM.sql
Using the Perl script version of rename
:
rename 's/\.sql$/-AM$&/' *.sql
Using the util-linux-ng
version of rename
(but only if ".sql" only appears at the end of the filename):
rename .sql -AM.sql *.sql
Using mmv
:
mmv '*.sql' '#1-AM.sql'