Al Phaba
Al Phaba

Reputation: 6785

How to extract a substring from a text file?

I have the following text file

testA=foo
testB=foobar
testC=Whatever

Now I want to extract the value for testB which is foobar. With my current PowerShell command I can only receive the whole line:

testB=foobar

My command is:

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

I could see that there is replace function for strings, so that you could replace testB= with empty string, but I do not know how to achieve this.

Upvotes: 6

Views: 11367

Answers (3)

Alexan
Alexan

Reputation: 8637

You can use Substring, for example:

$line = 'testB=foobar'
$res = $line.Substring($line.IndexOf('=')+1)

Upvotes: 1

4c74356b41
4c74356b41

Reputation: 72176

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

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 59031

You don't have to replace anything to capture the value. Instead, add a capture group to your search pattern. Then you are able to access the captured value:

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

Upvotes: 7

Related Questions