Reputation: 8602
I have a folder that contains a few .db
files and I am trying to create a shell script that copies every *.db
file but adds the current date to the file
For example, the folder contains A.db
, B.db
, C.db
. I want it to copy A.db
to /Backups/A_2016_07_21.db
and so on.
I know I can do cp -a A.db /Backups/A.db
but I am looking for a more automated way to do it for every *.db
file and also add the current date
Upvotes: 2
Views: 3183
Reputation: 1
You can use a one line for loop.
for file in $( ls /dir/*.db ); do cp $file /Backups/$( echo $file | cut -d. -f1 )_$( date +%Y_%m_%d ).$( echo $file | cut -d. -f2 ); done
Break down: for file in $( ls /dir/*.db ) - makes a list of all .db files
cp $file - copies the files (pretty self-explanatory)
/Backups/$( echo $file | cut -d. -f1 ) - extracts the first part of the filename. e.g. A.db -> A
$( date +%Y%m_%d ) - prints the date, with an underscore in front.
.$( echo $file | cut -d. -f2 ) - and finally extracts the last part of the filename with a prefix of "."
Upvotes: 0
Reputation: 42017
Iterate over the files using a for
construct and cp
files to the destination with getting desired file names using bash
parameter expansion and date
:
for f in *.db; do cp -a "$f" /Backups/""${f%.db}"_$(date '+%Y_%m_%d').db"; done
Upvotes: 4