正则表达式单次匹配问题:如何捕获指定echo语句的最后出现行
Hey there, let's sort out this regex problem for you. Let's start with your script context—you've got this shell code snippet, and you want to target only the specific line that outputs PB702101 not executed, not the extra lines your current regex is pulling in.
Here's your original script for reference:
if test ${csis_batch_completion} -le ${csis_batch_warning} ;then echo "Running PB702101" run ${csis_obj}/PB702101 display_completion else echo "PB702101 not executed" fi
The regex you're using right now is overcomplicated and ends up matching a range of lines because it's not properly anchored to the single line you care about. Let's fix that.
Solution 1: Match the exact line (single occurrence)
Use this simplified, precise regex that will only target the line you want:
^\s*echo "([^"]+) not executed"$
Let's break down why this works:
^: Anchors the match to the start of the line, so we don't match partial lines\s*: Accounts for any leading whitespace (like the indentation in your else block)echo ": Matches the literal start of the echo command with its opening quote([^"]+): Captures the variable prefix (like PB702101) by matching any character except a quote (so it stops at the closing quote of the first part)not executed": Matches the literal phrase followed by the closing quote$: Anchors the match to the end of the line, ensuring we only match the full line with this exact pattern
When you run this against your script, it will only return:
echo "PB702101 not executed"
Solution 2: Match the last occurrence (if multiple exist)
If you're working with a larger file where there might be multiple lines with this pattern and you specifically need the last one, use this PCRE-compatible regex (works in tools like grep -P, Perl, etc.):
(?s)^.*?^\s*echo "([^"]+) not executed"$
The extra parts here:
(?s): Enables "single line" mode, which allows the.character to match newlines^.*?: Non-greedily matches all content from the start of the file up until the last occurrence of our target line, ensuring we only capture the final instance
This will skip any earlier matching lines and grab only the last one.
内容的提问来源于stack exchange,提问作者Gutz

