Find numbers after specific text in a string with RegEx Find numbers after specific text in a string with RegEx powershell powershell

Find numbers after specific text in a string with RegEx


Try this expression:

"Error importing row no\. (\d+):"

DEMO

Here you need to understand the quantifiers and escaped sequences:

  • . any character; as you want only numbers, use \d; if you meant the period character you must escape it with a backslash (\.)
  • ? Zero or one character; this isn't what do you want, as you can here an error on line 10 and would take only the "1"
  • + One or many; this will suffice for us
  • * Any character count; you must take care when using this with .* as it can consume your entire input


Pretty straight forward. Right now your quoting is going to cause an error in the regex you wrote up. 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}


THere could be multiple ways , few simple ones shown below might help:-

I took your log in a file called temp.txt.

cat temp.txt | grep " Error importing row no." | awk -F":" '{print $2}' | awk -F"." '{print $2}'ORcat temp.txt | grep " Error importing row no." | sed  's/\(.*\)no.\(.*\):\(.*\)/\2/'