PowerShell Select-String来自带有Regex的文件

时间:2014-11-12 16:01:01

标签: regex string powershell substring

我正在尝试从.sln(Visual Studio解决方案文件)中获取一串文本,以显示解决方案中包含的项目文件。

示例文字行是

  

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

我感兴趣的字符串部分是\"之间的最后一部分。

\ partofname.Genesis.Printing.csproj"

我正在使用的正则表达式是:

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

我正在阅读文件内容:

$sln = gci .\Product\solutionName.sln

我不知道在我的字符串选择语句中放入什么。

我是PowerShell的新手,非常感谢任何帮助...

我确实有一个非常长期的方式来做到这一点,但我已经失去了工作......基本上它是为文件中的每一行做这个:

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

但正则表达式会更容易(我希望)。

2 个答案:

答案 0 :(得分:14)

以下内容包含"proj"之间的所有内容:

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

第一组获取proj文件所在的文件夹。第二组获取您所请求的文件名(项目文件名)。 AllMatches返回每个匹配,而不仅仅是第一个匹配。之后,只需循环匹配对象​​上的每个匹配集合,并获得匹配中第二组的值。

答案 1 :(得分:2)

你的脚本很棒。要在Select String:

上添加一个衬里添加-Path
Select-String -path $pathtoSolutionFile ', "([^\\]*?\\)?([^\.]*\..*proj)"' -
AllMatches | Foreach-Object {$_.Matches} | Foreach-Object {$_.Groups[2].Value}

要从中构建,您可以使用Groups [0]

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