I've got some files like this:
database1-backup-01-01-2011.sql
database2-backup-01-01-2011.sql...etc. I want to rename them to add AM, like this:
database1-backup-01-01-2011-AM.sql
database2-backup-01-01-2011-AM.sqlWhat's the most concise way to do that from the bash shell?
5 Answers
Another option:
for i in *.sql ; do mv -v $i ${i%.sql}-AM.sql
doneThis 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 9 Using the Perl script version of rename:
rename 's/\.sql$/-AM$&/' *.sqlUsing the util-linux-ng version of rename (but only if ".sql" only appears at the end of the filename):
rename .sql -AM.sql *.sqlUsing mmv:
mmv '*.sql' '#1-AM.sql' Since a Perl script has been suggested, here's a Ruby script to do the same:
`ls *.sql`.split("\n").each do |filename| new_filename = filename.split('.').join('-AM.') `mv #{filename} #{new_filename}`
end 1 I suggest to use qmv from renameutils
The qmv program will open list of filenames of choosen directory in your default text editor and allows you to edit them. When you save this edited file list, it applies new names to actual files.