toma, you may be interested in researching and reading up on
fsconcordance I don't think it does everything you want - but you may be able to modify it to fit your needs.
Update: Thanks to
HyperZonk the code can be d/l from
http://andromeda.rutgers.edu/~jlynch/fsc.pl