I have a string where I need to extract a substring from, but the end of my regex is repeated. I would like to sed to stop at the first instance of the end of my regex, much like instr() functions in many languages return the first instance.Example:echo This is a test some stuff I want string junk string end | sed -n 's/.*\(.te.*ng\).*/\1/p' returns: test some stuff I want string junk stringI want to return: test some stuff I want string
Extract a substring with sed that stops at the first occurrence of the end
sed;regular expression
grep approach (requires PCRE support):s=This is a test some stuff I want string junk string endgrep -Po 'te.*?ng' <<< $sAlternative perl approach:perl -ne 'print $&\n if /te.*?ng/' <<< $sThe output (for both approaches):test some stuff I want string.*? - ? here is non-greedy modifier, tells to match in minimal fashion