Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
646 views
in Technique[技术] by (71.8m points)

regex - 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)
question from:https://stackoverflow.com/questions/65870786/regex-in-powershell-outputing-things-outside-the-regex-match

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You may use

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

See the regex demo.

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

  • (?<=Equals*") - 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, '(?<=Equals*")[^"]+') | 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 = '(?<=Equals*")[^"]+'
Get-Content $file | 
     Select-String $regex -AllMatches | 
     Select-Object -Expand Matches | 
     ForEach-Object { $_.Value } |
     Set-Content $newfile

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...