djsnakz
djsnakz

Reputation: 478

PowerShell Regex Multilined

working with Regex and have hit a brick wall.

$AddressEdit = Select-String "c:\utilities\AddressStaged.txt" -pattern "^(?!<img src)"  | Select Line | Out-File "c:\utilities\Address.txt" 

Above returns some of the data I need. However, there is a line in the text file that always occurs right after this line that is returned that I also want to include in my output into a new document.

My Question: Is there a way for regex to say "Grab this line and also the line of data right below the one you have found from the pattern result"?

Upvotes: 1

Views: 164

Answers (1)

JPBlanc
JPBlanc

Reputation: 72610

Yes you can use RegEx with multilinematching using -Raw param of Get-Content.

I give this answer for the technical feasibility, for the operational point of view, you should follow @TheMadTechnician or @David Brabant advices.

Here is an XML file (M.txt):

<?xml version="1.0" encoding="utf-8"?>
<Machines xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Machine>
    <Nom>JPBHPP2.marceau.fr</Nom>
    <IP>192.168.2.61</IP>
    <Creation>2014-06-05T06:35:25.2318584+02:00</Creation>
    <Masque-IPv4>255.255.255.0</Masque-IPv4>
  </Machine>
  <Machine>
    <Nom>JPBASUSF2.marceau.fr</Nom>
    <IP>192.168.2.81</IP>
    <Creation>2014-06-05T06:35:20.7676768+02:00</Creation>
    <Masque-IPv4>255.255.255.0</Masque-IPv4>
  </Machine>
</Machines>

Now load the file as a single string:

$a = Get-Content D:\temp\M1.xml -Raw

Then try this RegEx :

$reg = [regex]'(?sm)  (<Nom>.*?</Nom>\r\n.*?\r\n)'

It gives :

$reg.Matches($a).count # gives 2
$reg.Matches($a).Groups[0].value
# gives 
#  <Nom>JPBHPP2.marceau.fr</Nom>
#    <IP>192.168.2.61</IP>

Updated to answer to your question : is it possible to start with a Regex and end with a regex and gather everything between? Here is a way to take everything between <Nom> and </IP>.

$reg = [regex]'(?sm)(<Nom>.*?</IP>)'

Upvotes: 2

Related Questions