0

我正在尝试从本机 PHP 中的所有脚本中提取所有 MySQL 查询。我希望仅使用 grep 从下面的查询中提取表名。以下是我的努力浪费在我想出的东西上。

FROM 'tablename'

FROM tablename

FROM apn.tablename

FROM apn.table_name

FROM 'apn.tablename'

grep -ionER "(FROM)[[:space:]](.*[a-zA-Z\d_.\`])[\s]"

重要的是 grep 捕获在表名结束后立即停止捕获文本,而我的 grep 没有。

我需要结果来显示这些信息:

(脚本位置):(行号):(表名)

/var/www/sites... : Line 31 : example_table_name

4

3 回答 3

4

Don't use grep. This is tailor-made job for Awk:

awk '$1 == "FROM" { print $2 }'

EDIT Thanks to @rojo for this suggestion

awk 'BEGIN{FS="from|FROM|where|WHERE"} /from|FROM/ {print $2}'

EDIT 2: WIth filename and line #

awk 'BEGIN{FS="from|FROM|where|WHERE"}
      /from|FROM/ {printf ("%s:%d:%s\n", FILENAME, NR, $2)}'
于 2013-03-30T04:09:28.123 回答
2

向后看会完成你想要的吗?

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.

于 2013-03-30T03:45:19.027 回答
0

我尝试了以下行。它将使用点、破折号和单引号来获取您的示例,并提取表名。您可以使用 grep/gawk/sed 部分并循环遍历您的 PHP 代码。

    echo "select * from 'the_db.the_table' where the_result=1;" | grep -ioE "(来自)[[:space:]]([a-zA-Z0-9\_\.\']*)[[:space:]]" | gawk '{ 打印 $2 }' | sed -es/\'//g

    the_db.the_table

于 2013-03-30T01:42:54.687 回答