我正在尝试在文件中查找模式。当我使用Select-String
我不想要整行得到匹配时,我只想要匹配的部分。
有没有我可以用来执行此操作的参数?
例如:
如果我这样做了
select-string .-.-.
该文件包含一行:
abc 1-2-3 abc
我想得到一个只有1-2-3的结果,而不是返回整行。
我想知道 Powershell 相当于grep -o
我正在尝试在文件中查找模式。当我使用Select-String
我不想要整行得到匹配时,我只想要匹配的部分。
有没有我可以用来执行此操作的参数?
例如:
如果我这样做了
select-string .-.-.
该文件包含一行:
abc 1-2-3 abc
我想得到一个只有1-2-3的结果,而不是返回整行。
我想知道 Powershell 相当于grep -o
要不就:
Select-String .-.-. .\test.txt -All | Select Matches
大卫走在正确的道路上。[regex] 是 System.Text.RegularExpressions.Regex 的类型加速器
[regex]$regex = '.-.-.'
$regex.Matches('abc 1-2-3 abc') | foreach-object {$_.Value}
$regex.Matches('abc 1-2-3 abc 4-5-6') | foreach-object {$_.Value}
如果太冗长,您可以将其包装在一个函数中。
我尝试了其他方法: Select-String 返回可以使用的属性匹配项。要获取所有匹配项,您必须指定 -AllMatches。否则它只返回第一个。
我的测试文件内容:
test test1 alk atest2 asdflkj alj test3 test
test test3 test4
test2
剧本:
select-string -Path c:\temp\select-string1.txt -Pattern 'test\d' -AllMatches | % { $_.Matches } | % { $_.Value }
返回
test1 #from line 1
test2 #from line 1
test3 #from line 1
test3 #from line 2
test4 #from line 2
test2 #from line 3
本着教人钓鱼的精神...
您要做的是将 select-string 命令的输出通过管道传输到Get-member,这样您就可以看到对象具有哪些属性。完成此操作后,您将看到“匹配项”,您可以通过将输出管道传输到| **Select-Object** Matches
.
我的建议是使用类似的东西:选择行号,文件名,匹配
例如:关于 stej 的样本:
sls .\test.txt -patt 'test\d' -All |select lineNumber,fileName,matches |ft -auto
LineNumber Filename Matches
---------- -------- -------
1 test.txt {test1, test2, test3}
2 test.txt {test3, test4}
3 test.txt {test2}
以上答案都不适合我。下面做了。
Get-Content -Path $pathToFile | Select-String -Pattern "'test\d'" | foreach {$_.Matches.Value}
Get-Content -Path $pathToFile | # Get-Content will divide into single lines for us
Select-String -Pattern "'test\d'" | # Define the Regex
foreach {$_.Matches.Value} # 只返回 Object 的 Matches 字段的值。(这允许多个结果匹配。)
代替管道,%
或者select
您可以使用更简单的.prop
成员枚举语法,它神奇地适用于多个元素:
(Select-String .-.-. .\test.txt -All).Matches.Value
或更少的括号:
$m = Select-String .-.-. .\test.txt -All
$m.Matches.Value
如果您不想使用 ForEach 运算符,则只能使用管道和Select -Expand
例如,要仅获取 之后的路径C:\
,您可以使用:
Get-ChildItem | Select-String -Pattern "(C:\\)(.*)" | Select -Expand Matches | Select -Expand Groups | Where Name -eq 2 | Select -Expand Value
Where Name -eq 2
只选择指定的正则表达式模式的第二个匹配项。
您可以使用 System.Text.RegularExpressions 命名空间:
http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.aspx