Reputation: 13
I am trying to write a powershell script to search for a pattern in a text file. Specifically I am looking at reading a file line by line and returning any line that has a space at the 32nd character position.
I have this so far but it just returns all lines that have white space. I need to narrow it down to the 32nd position
Get-Content -path C:\VM_names.txt | Where-Object {$_ -match "\s+"}
Upvotes: 0
Views: 3905
Reputation:
This is actually really easy to do. By default, Get-Content
reads a text file as an array of strings (individual lines), unless you use the -Raw
parameter, which reads it as a single string. You can use the -match
PowerShell operator to "match" the lines that meet your regular expression.
(Get-Content -Path c:\VM_names.txt) -match '^.{31}\s'
The result of the above command is an array of lines that match the desired regular expression.
NOTE: The call to Get-Content
must be wrapped in parentheses, otherwise the PowerShell parser will think that -match
is a parameter on that command.
NOTE2: As a good practice, use single quotes around strings, unless you specifically know that you need double quotes. You'll save yourself from accidental interpolation.
Upvotes: 1
Reputation:
Use this pattern:
-match '^.{31} '
Explanation:
^ - beginning of the string
. - any character
{31} - repeated 31 times
- a space
Upvotes: 1