简体   繁体   English

使用grep查找动态文本

[英]Using grep to find dynamic text

Need help with a bash script. 需要有关bash脚本的帮助。 We are modifying our database structure, the problem is we have many live sites that have pre-written queries referencing the current database structure. 我们正在修改数据库结构,问题是我们有许多实时站点具有预先编写的查询,这些查询引用了当前的数据库结构。 I need to find all of our scripts with references to MySQL tables. 我需要找到所有引用MySQL表的脚本。 Here is what I started: 这是我开始的:

grep -ir 'from' /var/www/sites/inspection.certifymyshop.com/ > resultsList.txt

I am trying to grep through our scripts recursively and export ALL table names found to a text file, we can use the "->from" and the "->join" prefixes to help us: 我试图递归地遍历我们的脚本并将所有找到的表名导出到文本文件,我们可以使用“-> from”和“-> join”前缀来帮助我们:

->from('databaseName.table_name dtn')  // dtn = table alias

OR 要么

->join('databaseName.table_name dtn')  // dtn = table alias

I need to find the database and table name within the single quotes (ie databaseName.table_name). 我需要在单引号内找到数据库和表名(即databaseName.table_name)。 I also need to list the filename this was found in underneath or next to the match like so: 我还需要列出在匹配项下方或旁边找到的文件名,如下所示:

someDatabaseName.someTableName | someDatabaseName.someTableName | /var/www/sites/blah.com/index.php | /var/www/sites/blah.com/index.php | line 36 36行

Try doing this : 尝试这样做:

grep -oPriHn -- "->(?:from|join)\('\K[^']+" . |
    awk -F'[ :]' '{print $3, "|", $1, "| line " $2}'

If this fits your needs, I can explain the snippet more as well. 如果这符合您的需求,我也可以进一步说明该代码段。

The one problem you have with only using grep is removing the from, join or whatever identifying prefix from the result. 仅使用grep的一个问题是从结果中删除from,join或任何标识前缀。 To fix this we can also use sed 为了解决这个问题,我们也可以使用sed

grep -EHroi -- '->(from|join)\('\''[^'\'' ]*' /path/to/files | sed -re 's/:.*(from|join)\('\''/:/g'

You could also use sed alone in a for loop 您也可以在for循环中单独使用sed

for i in `find /path/to/files -type f -print`
do
   echo $i
   sed -nre 's/^.*->(from|join)\('\''([^'\'' ]*)['\'' ].*$/\2/gp' $i
done

Edit: The above for loop breaks with filenames with spaces so here's the previous sed statement using find 编辑:上面的for循环使用带空格的文件名来中断,因此这是使用find的前一个sed语句

find ./ -type f -exec sh -c "echo {} ; sed -nre 's/^.*->(from|join)\('\''([^'\'' ]*)['\'' ].*$/\2/gp' \"{}\" ;" \;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM