Home > Software design >  Need to split 1st string before delimiter which is comma(,)
Need to split 1st string before delimiter which is comma(,)

Time:09-25

Need to split the 1st string before delimiter comma. For example

A="ABC:20.10.0-5,DEF:21.10.0-9,XYZ:20.10.0-9"

We need to extract 1st string before the comma(,) and the result should be like this -

B="ABC:20.10.0-5"

After this, I need to extract the numbers after colon(:) and before the dash(-). So the final value should be -

C="20.10.0"

CodePudding user response:

It can be done with simple shell substitution:

A="ABC:20.10.0-5,DEF:21.10.0-9,XYZ:20.10.0-9"
B="${A%%,*}" # Remove everything after the first comma and the comma itself
nodash="${B%%-*}" # Remove everything after the dash and the dash itself
C="${nodash##*:}" # Remove everything before the colon and the colon itself

CodePudding user response:

You can refer to the below code. I wasn't sure where exactly are you running it as there's only one tag and also that if you actually wanted to print double quotes in the output. Hence, i added them as well. I am assuming you are aware of cut command.

-bash-4.2$ cat test2.sh 
#!/bin/bash

A="ABC:20.10.0-5,DEF:21.10.0-9,XYZ:20.10.0-9"
echo "A="\"$A\"
B=`echo $A | cut -d"," -f1`
echo "B="\"$B\"
C=`echo $B | cut -d":" -f2 | cut -d"-" -f1`
echo "C="\"$C\"

-bash-4.2$ ./test2.sh 
A="ABC:20.10.0-5,DEF:21.10.0-9,XYZ:20.10.0-9"
B="ABC:20.10.0-5"
C="20.10.0"
  • Related