To give more detail, many regular expression functions like "
*" and "
+" are
greedy. That is, they always consume the
longest possible match. So "
.*-" means everything up to the last hyphen in the string. The pattern jschiwal gave is a common work-around; match everything that's
not a hyphen, so that the first hyphen encountered satisfies the expression.
And don't forget that the "
g" in sed is for "
global" matches, it will do the replacement on every match of the pattern in the string. Leave it off to only replace the first one. BTW, a little-known feature is that you can also use a number to specify which match on the line to replace. e.g.
sed 's/[^-]*-//2' will delete the part between the two hyphens (and the second hyphen).
If your string is stored in a shell variable, you can use a simple
parameter substitution instead. Unlike regex,
globbing patterns aren't naturally greedy.
Code:
line='The weather is - nice but rainy - cold'
echo "${line#*- }"