我需要识别分布在不同目录下许多文件中的 php 源代码中的所有查询。
我考虑过使用 grep 和 MySQL 关键字来识别它们。我可以通过两种方式区分此源代码中的查询。
- 它们总是用双引号引起来。
- 它们将始终具有 MySQL 关键字,例如
insert
、select
、update
、delete
和改变
。
但是有个问题,双引号里面的query可以分散到多行。示例:
$newQuery = "Select username
from
usertable"
所以我需要识别“Select username from usertable”
但是 grep 不能在多行上工作。
我试过了:
egrep -e '"(.*?)\+"' test.php | grep "select"
它适用于单行查询,但同样会错过多行查询。
所以我试过了
sed -e '/\"/,/\"/!d' test.php
它返回了所有的查询,但是我做了
sed -e '/\"/,/\"/!d' test.php | grep select
它返回,
"select
这不好。我想我需要在 sed 中转义换行符。我如何实现这一目标? bash 的任何其他标准命令也可以,例如 awk。
最佳答案
使用 Perl 的一种方法:
perl -00ne 'print $1,"\n" while (/"((select|insert|update|delete|alter).*?)"/sig);' file
获取单行输出:
perl -00ne 'while (/"((select|insert|update|delete|alter).*?)"/sig){$x=$1;$x=~s/\n//g;$x=~s/\s+/ /g;print "$x\n";};' file
使用 join 和 split 获得单行输出:
perl -00ne 'print join " ",split(/\s+/,$1),"\n" while (/"((select|insert|update|delete|alter).*?)"/sig);' file
关于regex - 使用 grep 在源代码中查找字符串中的所有查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15757685/