sed - last occurence of a match
Using sed, how do I remove everything after the last dash (-) in a string?
So how do I turn 'blah-blah-123' or 'blah-blah-blah-123' into 'blah-blah' or 'blah-blah-blah' respectively? -- mr. scary |
Code:
echo 'blah-blah-blah-123'| sed "s/-[^-]*$//" |
Moin,
regular expressions are greedy (they catch the longest part of a line, which matches the pattern), so this will work: Code:
jan@jack:~/tmp> echo 'blah-blah-blah-123' | sed -r 's/(.*)-.*/\1/' P.S.: The only one exception from the "greedy behaviour" is the "?" quantifier in Perl compatible regular expressions (not supported by grep and sed). |
Thank you jan61. That works (your explanation is a nice bonus). I did, however, need to escape the parentheses.
|
You can use a simple parameter substitution instead of sed:
Code:
$ string="blah-blah-blah-123" |
Ha. Changed to the parameter substitution solution instead. Great solutions guys.
|
Awww, I almost mentioned the parameter substitution thing myself, but decided against it because the OP specifically asked for a sed solution. Since substitution requires the use of a variable, it's less convenient than sed when doing things like working with a text file, and since the purpose of the change wasn't mentioned I decided not to presume. :(
This is a good example of why questions like this really ought to be goal-centered: "how can I accomplish x", rather than process-centered: "how can I make y do x". :) PS: If you use the -r switch in sed you don't need to escape the parentheses. |
Moin,
did you use the -r option (extended regex)? Jan |
All times are GMT -5. The time now is 12:29 PM. |