How to list the results of a regex search in a directory?

9

I have a directory with some C # files. In these files there are several SQL query codes.

I need to list all SELECT statements in these files using PowerShell. Commands start with SELECT and end with ; and can have more than one line, as an example:

SQL = "SELECT t.a, t.b, t.c FROM uf_GetResultSet(4, 1, 0, 0, 'G', 0, 0, 0) t";
(...)
SQL = "SELECT t.a, t.b, t.c" + 
      "FROM uf_GetResultSet(4, 3, 0, 0, 'C', " + idSomeThing.ToString() + ", 0, 0) t";

The default regex SELECT .+[\r\n]*.+"; fits me perfectly using Notepad ++, but I do not know how to adapt it in PS.

    
asked by anonymous 15.01.2014 / 15:04

3 answers

2

I came to the following command:

PS> select-string -path *.cs -pattern "(?smi)(?<sql>SELECT .+?);" | foreach {$_.matches} | foreach {$_.groups['sql']} | select value

But it returns the SELECTs of only one line.

    
15.01.2014 / 16:08
2

If you do not need to list the lines where the selects are, you can use the code below:

$arquivos = Get-Content *.cs | Out-String
$selects = [Regex]::Matches($arquivos, "(?si)(SELECT.+?;)")
$selects | Select-Object -Expand Value

Since you want to fetch SELECTs that start in one row and end in another, the first step is to turn the various Get-Content rows into one with the Out-String cmdlet.

The second step is to use the .NET System.Text.RegularExpressions.Regex class via the [Regex] accelerator, since it is able to return all matches of a string, unlike the -match operator.

    
13.02.2014 / 23:22
0

I do not quite understand what you want to do (because of foreachs), because you only have to use the select-string that will theoretically work: select-string -path * .cs -pattern "(? smi) (" SELECT. + ");"

    
29.01.2014 / 20:22