简体   繁体   English

PowerShell Select-String from file with Regex

[英]PowerShell Select-String from file with Regex

I am trying to get a string of text from a .sln (Visual Studio solution file) to show what project files are contained within the solution.我试图从 .sln(Visual Studio 解决方案文件)中获取一串文本,以显示解决方案中包含哪些项目文件。

An example line of text is文本的示例行是

Project("{xxxx-xxxxx-xxxx-xxxx-xx}") = "partofname.Genesis.Printing", "Production\\partofname.Genesis.Printing\\partofname.Genesis.Printing.csproj", "{xxx-xxx-xxx-xxx-xxxx}" EndProject Project("{xxxx-xxxxx-xxxx-xxxx-xx}") = "partofname.Genesis.Printing", "Production\\partofname.Genesis.Printing\\partofname.Genesis.Printing.csproj", "{xxx-xxx-xxx -xxx-xxxx}" 结束项目

The part of the string that I am interested in is the last part between the \\ and the " .我感兴趣的字符串部分是\\"之间的最后一部分。

\\partofname.Genesis.Printing.csproj" \\partofname.Genesis.Printing.csproj"

The regular expression I am using is:我使用的正则表达式是:

$r = [regex] "^[\\]{1}([A-Za-z.]*)[\""]{1}$"

I am reading the file content with:我正在阅读文件内容:

$sln = gci .\Product\solutionName.sln

I don't know what to put in my string-select statement.我不知道在我的字符串选择语句中放什么。

I am very new to PowerShell and would appreciate any and all help...我是 PowerShell 的新手,希望得到任何帮助...

I did have a very very long-hand way of doing this earlier, but I have lost the work... Essentially it was doing this for each line in a file:我之前确实有一个非常非常长的方法,但我已经失去了工作......本质上它是对文件中的每一行执行此操作:

Select-String $sln -pattern 'proj"' | ? {$_.split()}

But a regular expression would be a lot easier (I hope).但是正则表达式会容易得多(我希望)。

The following gets everything between " and proj" :以下获取"proj"之间的所有内容:

Select-String -Path $PathToSolutionFile ', "([^\\]*?\\)*([^\.]*\..*proj)"' -AllMatches | Foreach-Object {$_.Matches} | 
       Foreach-Object {$_.Groups[2].Value}

The first group gets the folder that the proj file is in. The second group gets just was you requested (the project file name).第一组获取项目文件所在的文件夹。第二组获取您所请求的(项目文件名)。 AllMatches returns every match, not just the first. AllMatches返回每场比赛,而不仅仅是第一场比赛。 After that it's just a matter of looping through each collection of matches on the match objects and getting the value of the second group in the match.之后,只需遍历匹配对象上的每个匹配集合并获取匹配中第二组的值即可。

Your Script works great.你的脚本很好用。 To make into a one liner add -Path on the Select String:要使其成为单行,请在 Select String 上添加 -Path:

Select-String -path $pathtoSolutionFile ', "([^\\]*?\\)?([^\.]*\..*proj)"' -
AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[2].Value}

To build from this you can use Groups[0]要从中构建,您可以使用 Groups[0]

(((Select-String -path $pathtoSoultionFile ', "([^\\]*?\\)?([^\.]*\..*proj)"' -AllMatches | Foreach-Object {$_.Matches} | 
       Foreach-Object {$_.Groups[0].Value})-replace ', "','.\').trim('"'))

对我来说,这种模式是最好的: [^"]+\\.csproj

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

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