Substring based on delimiter, finding last delimiter

Hi,

I have a string like ABC.123.XYZ-A1-B2-P1-C4. I want to delimit the string based on "-" and then get result as only two strings. One with string till last hyphen and other with value after last hyphen... For this case, it would be something like first string as "ABC.123.XYZ-A1-B2-P1" and secod string as C4.
How can we achieve it? I am using /bin/sh shell.

Thanks for your help.

hello
you can employ perl in your script easily as perl is extremely portable with monstrous regex capabilities. In this I use the greedy quantifier.

 echo "ABC.123.XYZ-A1-B2-P1-C4 " | perl -wln -e 'print "$1 $2" if /^(.*)\-(.*)$/'
ABC.123.XYZ-A1-B2-P1 C4 
 

regards.

Gaorav
Can you explain this?

if /^(.*)\-(.*)$/

tene..
first I am Gaurav not Gaorav...
well you would have to look at the regex(especially perl's) to understand what they are.
I will explain in short here
. -> a single character except '\n'

  • -> 0 or more occurence of the previous character(s)
    ^ -> start of the string
    $ -> end of the string
    if you have perl installed then do
#perldoc perlretut

shell

INPUT="ABC.123.XYZ-A1-B2-P1-C4"
OUT1=${INPUT%-*}
OUT2=${INPUT##*-}

using sed,

$ echo "ABC.123.XYZ-A1-B2-P1-C4" | sed 's/\(.*\)-\(.*\)/\1 \2/'

Python

>>> string="ABC.123.XYZ-A1-B2-P1-C4"
>>> first,last = string.rsplit("-",1)
>>> print first
ABC.123.XYZ-A1-B2-P1
>>> print last
C4
>>>

---------- Post updated at 07:30 AM ---------- Previous update was at 07:30 AM ----------

Python

>>> string="ABC.123.XYZ-A1-B2-P1-C4"
>>> first,last = string.rsplit("-",1)
>>> print first
ABC.123.XYZ-A1-B2-P1
>>> print last
C4
>>>