I have a text file containing lines of data. I can use the following powershell script to extract the lines I’m interested in:
select-string -path *.txt -pattern 'subject=([A-Z\.]+),'
Some example data would be:
blah blah subject=THIS.IS.TEST.DATA, blah blah blah
What I want is to be able to extract just the actual contents of the subject (i.e. the ‘THIS.IS.TEST.DATA’ string). I tried this:
select-string -path *.txt -pattern 'subject=([A-Z\.]+),' | %{ $_.Matches[0] }
But the ‘Matches’ property is always null. What am I doing wrong?
I don’t know why your version doesn’t work. It should work. Here is an uglier version that works.
Explanation:
-matchis a regular expression matching operator:The
> $nulljust suppresses the True being written to the output. (Try removing it.) There is a cmdlet that does the same thing whose name I don’t recall at the moment.$matchesis a magic variable that holds the result of the last-matchoperation.