Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

find file names that return success on -exec command

I am using find to find names of databases that return some rows for a query.

$ find . -name 'sqlite.db' -exec sqlite3 "{}" 'SELECT * FROM table WHERE column1="value"' \; 

value|a|b|c|d

But I want the name of the database, so I tried -print which showed all the names

$ find . -name 'sqlite.db' -print -exec sqlite3 "{}" 'SELECT * FROM table WHERE column1="value"' \; 

/dir1/a/sqlite.db
value|a|b|c|d
/dir2/a/sqlite.db
/dir2/b/sqlite.db
/dir3/a/sqlite.db

Is there a way I can get only the files where the exit status of the command run is success.

like image 438
Himanshu Avatar asked Jan 30 '13 07:01

Himanshu


2 Answers

You just need to -print after the -exec. It is a short circuiting boolean and, and by putting -print before -exec, the print happens before the exec does.

find . -name sqlite.db -exec ... \; -print
like image 136
William Pursell Avatar answered Oct 28 '22 23:10

William Pursell


sqite3 returns 0 even when there is not data is found matching the criteria. It returns false only when there is a error in the sql statement itself or in the arguments passed.

sqlite3 sqlite.db 'SELECT * FROM table WHERE column1="value"'

will return 0 even there is no matchin column in the database. You can combine command with grep for the find to work.

sqlite3 sqlite.db 'SELECT * FROM table WHERE column1="value" | grep value

so your find command becomes

find . -name 'sqlite.db' -exec sqlite3 "{}" 'SELECT * FROM table WHERE column1="value"' | grep value \;

EDIT:

The above doesn't work since exec cannot handle pipes. see How do I include a pipe | in my linux find -exec command?

find . -name "*.db" -type f | while read file ; do sqlite3 $file "SELECT * FROM table WHERE column1='value'" | grep value ; if [ $? -eq 0 ] ; then echo $file ; fi done

This I have tested and it works, but I am not sure whether this is the solution you are looking for.

like image 31
Santosh Avatar answered Oct 29 '22 01:10

Santosh