Rob Welch
Rob Welch

Reputation: 11

Unix/Bash: Redirect results of find command so files are used as input for other command

I've got a directory structure that contains many different files named foo.sql. I want to be able to cd into this directory & issue a command like the following:

find . -name "foo.sql" -exec mysql -uUserName -pUserPasswd < {} \;

where {} is the relative path to each foo.sql file. Basically, I want:

mysql -uUserName -pUserPasswd < path/to/foo.sql

to be run once for each foo.sql file under my subdirectory. I've tried Google & it's been not much help. Ideally this would be part of a UNIX shell script.

Thanks in advance, & sorry if it's been asked before.

Upvotes: 0

Views: 777

Answers (2)

keshlam
keshlam

Reputation: 8058

Or, just to point out another approach:

find . | xargs cat | mysql etcetera

xargs is a generic pipe operation roughly equivalent to find's '-exec'. It has some advantages, some disadvantages, depending on what you're doing. Intend to use it because i'm often filtering the list of found files in an earlier pipeline stage before operating on them.

There are also other ways of assembling such command lines. One nice thing about Unix's generic toolkits is that there are usually multiple solutions, each with its own tradeoffs.

Upvotes: 0

Barmar
Barmar

Reputation: 780929

The -exec option doesn't run a shell, so it can't process shell operators like redirection. Try this:

find . -name "foo.sql" -exec cat {} + | mysql -uUserName -pUserPasswd 

cat {} will write the contents of all the files to the pipe, which will then be read by mysql.

Upvotes: 1

Related Questions