AngryHacker
AngryHacker

Reputation: 61636

How to split a string on the second match

I have a string:

foo="re-9619-add-selling-office";

I'd like to break up the string on the second - (dash) into variable1 and variable2. I want to end up with variable1=re-9619 and variable2=add-selling-office

I tried it using grep and awk, but now I not sure that's the way to go.

Upvotes: 0

Views: 1394

Answers (4)

RavinderSingh13
RavinderSingh13

Reputation: 133600

Could you please try following once. Where first variable will have value like re-9619 and second shell variable will have value like add-selling-office

first=$(echo "$foo" | sed 's/\([^-]*-[^-]*\)-.*/\1/')
second=$(echo "$foo" | sed 's/\([^-]*\)-\([^-]*\)-\(.*\)/\3/')

Explanation:

  • echo "$foo" | sed 's/\([^-]*-[^-]*\)-.*/\1/': Printing value of foo variable and passing its output to sed command. In sed I am using substitute capability to perform substitution, \([^-]*-[^-]*\)-.*(which has everything from starting of value to till 2nd occurrence of - in back reference in it). Then substituting whole value with 1st captured back reference value which will become only re-9619.
  • echo "$foo" | sed 's/\([^-]*\)-\([^-]*\)-\(.*\)/\3/': Logic is same as above mentioned command. Using sed's capability of substitution with using back reference capability of it. Here we are printing everything after 2nd occurrence of -.

NOTE: second=$(echo "$foo" | sed -E "s/$first-(.*)/\1/") could also help as per @User123's comments.

Upvotes: 2

PieCot
PieCot

Reputation: 3639

You can use cut:

variable1=$(echo $foo | cut -d '-' -f 1-2)
variable2=$(echo $foo | cut -d '-' -f 3-)

This is the result:

>> echo $variable1
re-9619
>> echo $variable2
add-selling-office

Upvotes: 1

oguz ismail
oguz ismail

Reputation: 50785

That can be done using parameter expansions, you don't need an external utility.

$ foo="re-9619-add-selling-office"
$ variable2=${foo#*-*-}
$ variable1=${foo%-"$variable2"}
$
$ echo $variable1
re-9619
$ echo $variable2
add-selling-office

Upvotes: 1

anubhava
anubhava

Reputation: 785481

Here is a single sed + read way:

foo="re-9619-add-selling-office"
read var1 var2 < <(sed -E 's/^([^-]*-[^-]*)-/\1 /' <<< "$foo")

# check variables
declare -p var1 var2
declare -- var1="re-9619"
declare -- var2="add-selling-office"

Upvotes: 2

Related Questions