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

Asked

Viewed 763 times

9

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

I need to list all SELECT commands in these files using Powershell. The commands start with SELECT and end with ; and may have more than one line, as the 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 regex standard SELECT .+[\r\n]*.+"; fits me perfectly using Notepad++, but I don’t know how to adapt it in PS.

3 answers

2

If you don’t need to list the lines the selects are on, 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 search for Selects that start in one row and end in another, the first step is to turn the various lines of Get-Content into one, with cmdlet Out-String.

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

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.

0

I don’t understand very well what you want to do (the why of foreachs), because it is only using the select-string that will theoretically work : select-string -path *.Cs -Pattern "(? smi)(? SELECT .+?);"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.