Reputation: 53
I am trying to split a string in unix shell script, but I am not able to figure out. Any help would be appreciated. Below is the example
olap4j-xmla-1.0.1.500,
olap4j-xmla-1.2.0,
olap4j-xmla-1.2.0.SNAPSHOT,
olap4j-xmla-1.2.0.RELEASE
The above strings will be split so that the output will be stored in different variables like
var1=olap4j-xmla var2=1.0.1.500
var1=olap4j-xmla var2=1.2.0
var1=olap4j-xmla var2=1.2.0 var3=SNAPSHOT
var1=olap4j-xmla var2=1.2.0 var3=RELEASE
Upvotes: 1
Views: 78
Reputation: 766
#!/bin/bash
while read LINE; do
var1=$(cut -d '-' -f1,2 <<< "$LINE")
tmp=$(cut -d '-' -f3 <<< "$LINE")
var2=$(sed 's/\(.*\)\.[a-zA-Z]*$/\1/' <<< "$tmp")
var3=$(sed -n 's/.*\.\([a-zA-Z]*$\)/\1/p' <<< "$tmp")
echo -e "var1=$var1; var2=$var2; var3=$var3"
done < file.txt
Output:
var1=olap4j-xmla; var2=1.0.1.500; var3=
var1=olap4j-xmla; var2=1.2.0; var3=
var1=olap4j-xmla; var2=1.2.0; var3=SNAPSHOT
var1=olap4j-xmla; var2=1.2.0; var3=RELEASE
Upvotes: 0
Reputation: 785098
Using string substitutions:
s='olap4j-xmla-1.0.1.500'
read var1 var2 <<< "${s%-*} ${s##*-}"
Now check variables:
declare -p var1 var2
declare -- var1="olap4j-xmla"
declare -- var2="1.0.1.500"
Update:
Thanks to comment from pjh below I have realized that OP needs 3 variable for some cases instead of 2.
Looking at that I think following sed
will work better:
sed -E 's/^(.+)-([0-9.]+)(\.([^0-9]+))?$/\1 \2 \4/' <<< "olap4j-xmla-1.2.0.SNAPSHOT"
olap4j-xmla 1.2.0 SNAPSHOT
sed -E 's/^(.+)-([0-9.]+)(\.([^0-9]+))?$/\1 \2 \4/' <<< "olap4j-xmla-1.2.0"
olap4j-xmla 1.2.0
Output of sed
can be fed into read
as shown in above examples.
Upvotes: 3