Would a lookbehind accomplish what you want?
grep -P -i -o '(?<=from )\S+' *.php | sed -r 's/^\W|\W$//g'
Update:
If you want the file name and the line number printed as well, you'll probably need a for
loop:
for i in `grep -R --include=*.php -l -i 'FROM' /var/www/sites`; do grep -Pion '(?<=from )\S+' $i | sed -r -e "s/['\`\"]/ /g" -e 's#^#'$i'... : line #'; done
This works as follows:
- for each file in
grep
recursive, print file name, case insensitive search for FROM
in *.php
- do
- look for non-spaces following
"from "
, print only line number and matching word
- use
sed
to replace '"`
with a space and insert the filename at the beginning of the line
Example session:
rojo@pico:~$ cat Desktop/test.php
' SELECT * FROM `contacts` WHERE 1=1' test data here that should be cut out'
rojo@pico:~$ for i in `grep -R --include=*.php -l -i 'FROM' .`; do grep -Pion '(?<=from )\S+' $i | sed -r -e "s/['\`\"]/ /g" -e 's#^#'$i'... : line #'; done
./Desktop/test.php... : line 1: contacts
Here's another alternative using awk
:
find /var/www/sites -type f -iname '*.php' -print0 | xargs -0 awk 'BEGIN {FS="from|FROM|where|WHERE"} {++x;} /from|FROM/ {printf "%s... : line %d : %s%s", FILENAME, x, $2, ORS}'
... But I haven't figured out how to make it strip quotes / backticks / apostrophes surrounding the table names. I could probably pipe it through sed
or tr
if it's important, but there has to be a more graceful way to do it.