CDP-cdp
CDP-cdp

Reputation: 75

Powershell how to split string after or before ('/')

I have a usecase that I would like to split. Below is the output of a program in a txt file. I need the VALUE part alone to be written in another txt file to be read by another process.

OUTPUT: "Id": "/Name/VALUE",

I tried

$text.split('/')[1].split(' ')

but it resulted in giving me "Name"
On the whole, what am I doing is

$text = Get-Content C:\temp\file.txt
$text.split('/')[1].split(' ') | Out-File C:\temp\file1.txt

Upvotes: 0

Views: 932

Answers (3)

mklement0
mklement0

Reputation: 439267

To complement TessellatingHeckler's helpful answer with solutions based only on PowerShell's own -split and -replace operators:

PS> ('OUTPUT: "Id": "/Name/VALUE"' -split '/')[-1] -replace '"'
VALUE

Array index -1 extracts the last element from the array of /-separated tokens that -split '/' outputs, and -replace '"' then removes any " instances from the result (in the absence of a replacement string, replaces them with the empty string, thereby effectively removing them).


With the help of a regex (regular expression), using -replace by itself is sufficient:

PS> 'OUTPUT: "Id": "/Name/VALUE"' -replace '.*/(.*?)"', '$1'
VALUE
  • .*/ greedily matches everything up to the last /
  • (.*?)" non-greedily matches everything until a " is encountered; since .*? is enclosed in (...), it is a so-called capture group that makes the sub-match available as $1 in the replacement string.

Upvotes: 0

Esperento57
Esperento57

Reputation: 17472

Method 1 with array of delimiter:

$content.split(@('"', '/'))[5]

Method 2 with multi split:

$content.split('"')[3].Split('/')[2]

Upvotes: 0

TessellatingHeckler
TessellatingHeckler

Reputation: 29033

Do it step by step and look at the results, you'll see that

PS C:\> 'OUTPUT: "Id": "/Name/VALUE",'.Split('/')
OUTPUT: "Id": "
Name
VALUE",

The first line is index 0, the second line (Name) is index 1, the third line (VALUE",) is index 2.

You could get the VALUE by:

$text.Split('/')[2].Replace('",', '')

To take the Value line and remove the quote and comma.

Upvotes: 1

Related Questions