Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract string from text file via Powershell

I have been trying to extract certain values from multiple lines inside a .txt file with PowerShell.

Host
Class
INCLUDE vmware:/?filter=Displayname Equal "server01" OR Displayname Equal "server02" OR Displayname Equal "server03 test"

This is what I want :

server01
server02
server03 test

I have code so far :

$Regex = [Regex]::new("(?<=Equal)(.*)(?=OR")           
$Match = $Regex.Match($String)
like image 755
Arbelac Avatar asked Jan 27 '23 18:01

Arbelac


1 Answers

You may use

[regex]::matches($String, '(?<=Equal\s*")[^"]+')

See the regex demo.

See more ways to extract multiple matches here. However, you main problem is the regex pattern. The (?<=Equal\s*")[^"]+ pattern matches:

  • (?<=Equal\s*") - a location preceded with Equal and 0+ whitespaces and then a "
  • [^"]+ - consumes 1+ chars other than double quotation mark.

Demo:

$String = "Host`nClass`nINCLUDE vmware:/?filter=Displayname Equal ""server01"" OR Displayname Equal ""server02"" OR Displayname Equal ""server03 test"""
[regex]::matches($String, '(?<=Equal\s*")[^"]+') | Foreach {$_.Value}

Output:

server01
server02
server03 test

Here is a full snippet reading the file in, getting all matches and saving to file:

$newfile = 'file.txt'
$file = 'newtext.txt'
$regex = '(?<=Equal\s*")[^"]+'
Get-Content $file | 
     Select-String $regex -AllMatches | 
     Select-Object -Expand Matches | 
     ForEach-Object { $_.Value } |
     Set-Content $newfile
like image 63
Wiktor Stribiżew Avatar answered Feb 07 '23 14:02

Wiktor Stribiżew