向后看会完成你想要的吗?
grep -P -i -o '(?<=from )\S+' *.php | sed -r 's/^\W|\W$//g'
更新:
如果您还想打印文件名和行号,您可能需要一个for
循环:
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
这工作如下:
- 对于每个文件
grep
递归,打印文件名,不区分大小写的FROM
搜索*.php
- 做
- 查找后面的非空格
"from "
,仅打印行号和匹配的单词
- 用于
sed
替换'"`
为空格并在行首插入文件名
示例会话:
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
这是另一种使用方法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.