Reputation: 67
I have a text file and I want to display a content from the file after searching for a word pattern.
My text file has following
Hello 2013, a7
Hello 2013, z8
errorprocessing adafda adasd adads adasdad adadsasd asdadsdasd adasdasdasda dadsadasda
Hello 2013, e1
My display should be
user: z8
error: errorprocessing adafda adasd adads adasdad adadsasd asdadsdasd adasdasdasda dadsadasda
I could search errorproceesing pattern and display the content but I am unable to display xyz008 as this is a dynamic word and it may differ from one text file to another.
I need to search for
Hello [0-9][0-9][0-9][0-9][a-z][0-9]
But I am not able get the desired output
I want to implement in Powershell I have Select-String -Pattern [0-9][0-9][0-9][0-9][A-Z][0-9] -AllMatches -SimpleMatch –
Upvotes: 1
Views: 78
Reputation: 439193
Try the following (substitute your input filename for file
):
do { # Dummy loop so we can exit the pipeline prematurely with `break`.
get-content file | % {
if ($_ -match '^Hello (\d{4}), ([a-z0-9]+)$') { # username found
# Save it.
$userName = $matches[2]
} elseif ($_ -match '^errorprocessing ') { # error line found
# Output desired result.
"user: $userName`r`nerror: $_"
# Exit pipeline (via dummy loop).
break
}
}
} while ($false)
Note: The assumption is that you want to display only one username, namely the most recent one preceding the error line.
Select-String
will not match across lines.break
before processing ALL lines, it had to be wrapped in a (dummy) loop).Upvotes: 2