LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Desktop (https://www.linuxquestions.org/questions/linux-desktop-74/)
-   -   sed - last occurence of a match (https://www.linuxquestions.org/questions/linux-desktop-74/sed-last-occurence-of-a-match-704206/)

mr_scary 02-12-2009 11:10 AM

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

David the H. 02-12-2009 11:39 AM

Code:

echo 'blah-blah-blah-123'| sed "s/-[^-]*$//"
Matches a hyphen, then any number of characters except a hyphen, until the end of the line. This means that only the last occurrence of the hyphen satisfies the string.

jan61 02-12-2009 11:39 AM

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/'
blah-blah-blah

Jan

P.S.: The only one exception from the "greedy behaviour" is the "?" quantifier in Perl compatible regular expressions (not supported by grep and sed).

mr_scary 02-12-2009 02:21 PM

Thank you jan61. That works (your explanation is a nice bonus). I did, however, need to escape the parentheses.

colucix 02-12-2009 02:23 PM

You can use a simple parameter substitution instead of sed:
Code:

$ string="blah-blah-blah-123"
$ string=${string%-*}
$ echo $string
blah-blah-blah


mr_scary 02-12-2009 06:22 PM

Ha. Changed to the parameter substitution solution instead. Great solutions guys.

David the H. 02-12-2009 11:58 PM

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.

jan61 02-13-2009 12:44 PM

Moin,

did you use the -r option (extended regex)?

Jan


All times are GMT -5. The time now is 12:29 PM.