Linux – Copy files from sub directories into one directory

command-line-interfacelinuxshell

Ok I have a bunch of files in this file structure format.

/backup/daily/database1/database1-2011-01-01.sql
/backup/daily/database1/database1-2011-01-02.sql
/backup/daily/database1/database1-2011-01-03.sql
/backup/daily/database1/database1-2011-01-04.sql
/backup/daily/database1/database1-2011-01-05.sql
/backup/daily/database1/database1-2011-01-06.sql
/backup/daily/database1/database1-2011-01-07.sql
/backup/daily/anotherdb/anotherdb-2011-01-01.sql
/backup/daily/anotherdb/anotherdb-2011-01-02.sql
/backup/daily/anotherdb/anotherdb-2011-01-03.sql
/backup/daily/anotherdb/anotherdb-2011-01-04.sql
/backup/daily/anotherdb/anotherdb-2011-01-05.sql
/backup/daily/anotherdb/anotherdb-2011-01-06.sql
/backup/daily/anotherdb/anotherdb-2011-01-07.sql
/backup/daily/stuff/stuff-2011-01-01.sql
/backup/daily/stuff/stuff-2011-01-02.sql
/backup/daily/stuff/stuff-2011-01-03.sql
/backup/daily/stuff/stuff-2011-01-04.sql
/backup/daily/stuff/stuff-2011-01-05.sql
/backup/daily/stuff/stuff-2011-01-06.sql
/backup/daily/stuff/stuff-2011-01-07.sql

And there are lots lots more.

ultimately I want to import all the 2011-01-07.sql files into my mysql database.

This works for one

mysql -u root -ppassword < /backup/daily/database1/database1-2011-01-07.sql

That will nicely restore that database from this backupfile.

I want to run a process where it does this for all databases.

So my plan is to first cp all 2011-01-07 sql files into a tmp dir e.g.

cp /backup/daily/*/*2011-01-07*.sql /tmp/all

The command above unfortunately isn't working I get an error:

cp: cannot stat ….. No such file or directory

So can you guys help me out with this. For bonus points if you can tell me how to do the next step which is import all databases in one command doing one at a time that would be great too.

I really want to do these in two separate steps because I need to delete a few sql files manually from the tmp dir before I run the restore command.

So I need:

1) command to copy all 2011-01-07 sql files to a tmp dir

2) command to import all those files in that dir into mysql

I know its possible to do in one but for lots of reasons I really would prefer to do it in two steps.

Best Answer

To copy all the 2011-01-07 sql files to a temporary directory (/tmp/all as per question)

find /backup/daily -name '*-2011-01-07.sql' -exec cp -t /tmp/all {} +

to import

#!/bin/bash
for FILE in $( ls /tmp/all/*-2011-01-07.sql )
do
    echo "Importing $FILE ... "
    mysql -u root -ppassword < "$FILE" && echo "OK"
done