如何从文本文件中提取子字符串?

6
我有一个文本文件,其内容如下:
testA=foo
testB=foobar
testC=Whatever

现在我想要提取testB的值,也就是foobar。使用我当前的PowerShell命令,我只能得到整行的内容:

testB=foobar

我的命令是:

Select-String -Path .\test.txt -Pattern "testB=" -List

我看到字符串有替换函数,可以将testB=替换为空字符串,但我不知道如何实现。
3个回答

7

您无需更改任何内容即可捕获值。相反,只需向搜索模式添加一个捕获组即可。然后您就能够访问所捕获的值:

(Select-String -Path $scripts.tmp -Pattern "testB=(.*)").Matches.Groups[1].Value

啊,好的。我怎样才能额外地修剪这个值? - Al Phaba
.Matches.Groups[1].Value后面添加 .Trim() 即可。 - Martin Brandl
1
应该使用 .Matches[0].Groups 而不是 .Matches.Groups。 - Sergey Enns

1
(Get-Content | where {$_ -like "testB*"}).Replace('testB=','')

抱歉,打错了;( - 4c74356b41

1
你可以使用 Substring,例如:
$line = 'testB=foobar'
$res = $line.Substring($line.IndexOf('=')+1)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接