Tuesday, April 19, 2011

Bash Script - MYSQL query (match files in directory with certain files in db table)

Get all files in a directory, compare it to filenames stored in database, where a condition is met and return only the filenames that match that condition.



#!/bin/bash

##GET & LOOP THROUGH FILES IN DIRECTORY##
cd /path/to/directory/
##FIND ALL TEXT FILES##
FILES=*.txt
for f in $FILES
do

##GET TXT FILENAME##
TXTFNAME="$f"

##ALTER IF NECESSARY##
export TXTFNAME1=`echo $TXTFNAME | sed -e 's/fromthis/tothis/g'`

##MYSQL QUERY##
variable=`
mysql -u username --password=password << eof
use databasename;
SELECT column FROM table WHERE column='keyword';
eof`

##IF FILENAME EQUALS FILENAME IN DB##
if [[ $variable =~ .*$TXTFNAME1.* ]]; then

echo $TXTFNAME1 is a match


fi

#end of loop#
done

No comments: