Find numbers after specific text in a string using RegEx
I have a multi-line string such as:
2012-15-08 07:04 Bla bla bla blup
2012-15-08 07:05 *** Error importing row no. 5: The import of this line failed because bla bla
2012-15-08 07:05 Another text that I don't want to search...
2012-15-08 07:06 Another text that I don't want to search...
2012-15-08 07:06 *** Error importing row no. 5: The import of this line failed because bla bla
2012-15-08 07:07 Import has finished bla bla
I want to extract all line numbers with errors using the RegularExpression function (using PowerShell). So I need to find the number between "*** Error importing line #" and the following ":" as this will always give me the line number.
I have looked at various RegEx questions, but honestly, the answers are similar to the Chinese for me.
Tried to create RegEx using http://regexr.com/ but not successful so far, for example with the following pattern:
"Error importing row no. "(.?)":"
Any hints?
source to share
Try the following expression:
"Error importing row no\. (\d+):"
This is where you need to understand quantifiers and escaped sequences:
-
.
any character; since you only want numbers, use\d
; if you meant a period character, you must escape it with a backslash (\.
) -
?
Zero or one character; this is not what you want as here you can enter an error on line 10 and only take "1" -
+
One or many; this will be enough for us -
*
Any number of characters; you should take care using this with a help.*
as it can consume all of your input.
source to share
Pretty straight forward. Right now, your quoting will throw an error in the regex you wrote. Try this instead:
$LogText = ""#Your logging stuff
[regex]$Regex = "Error importing row no\. ([0-9]*):"
$Matches = $Regex.Matches($LogText)
$Matches | ForEach-Object {
$RowNum = $_.Groups[1].Value #(Waves hand) These are the rows you are looking for
}
source to share
There can be several ways, a few simple ones shown below can help: -
I took your log into a file called temp.txt.
cat temp.txt | grep " Error importing row no." | awk -F":" '{print $2}' | awk -F"." '{print $2}'
OR
cat temp.txt | grep " Error importing row no." | sed 's/\(.*\)no.\(.*\):\(.*\)/\2/'
source to share