How to extract part of a variable to another variable in a shell script

I have a variable that looks like xx-xx-xx-xx, where each xx is a number (the length of each xx is unknown)

I need to extract these numbers into separate variables so that they can be manipulated. I tried to look at regular expressions, but could not see any solution (or I'm blind enough not to notice).

The perfect solution should look like

#!/bin/sh # assume VARIABLE equals 1234-123-456-890 VARIABLE=$1 # HERE SOME CODE assigning variables $PART1 $PART2 $PART3 $PART4 echo $PART1-$PART2-$PART3-$PART4 # Output will give us back 1234-123-456-890 

I'm new to shell scripting, so I might have missed something.

+4
source share
5 answers

Using bash , you can use an array like this:

 #!/bin/bash VARIABLE=1234-123-456-890 PART=(${VARIABLE//-/ }) echo ${PART[0]}-${PART[1]}-${PART[2]}-${PART[3]} 

The extension ${VARIABLE//-/ } changes everything - to spaces, and then breaks the word boundaries into an array.

Alternatively, you can use read :

 #!/bin/bash VARIABLE=1234-123-456-890 read PART1 PART2 PART3 PART4 <<< "${VARIABLE//-/ }" echo $PART1-$PART2-$PART3-$PART4 

To make it work in sh , you can slightly modify it and set IFS , the input field separator:

 #!/bin/sh VARIABLE=1234-123-456-890 old_ifs="$IFS" IFS=- read PART1 PART2 PART3 PART4 <<EOF $VARIABLE EOF IFS="$old_ifs" echo $PART1-$PART2-$PART3-$PART4 

Caution: this was tested only with bash in sh mode.

+11
source

/bin/sh dash (see "Extending Options")

 #!/bin/sh # assume VARIABLE equals 1234-123-456-890 VARIABLE="$1" PART4="$VARIABLE" # PART4 is 1234-123-456-890 PART1="${PART4%%-*}" # PART1 is 1234 PART4="${PART4#*-}" # PART4 is 123-456-890 PART2="${PART4%%-*}" # PART2 is 123 PART4="${PART4#*-}" # PART4 is 456-890 PART3="${PART4%%-*}" # PART3 is 456 # PART4 is 456-890 PART4="${PART4#*-}" # PART4 is 890 echo "$PART1-$PART2-$PART3-$PART4" 

Test for $PART1-$PART2-$PART3-$PART4

 $ ./test.sh 1234-123-456-890 1234-123-456-890 $ ./test.sh 1234-abc-789-ABCD 1234-abc-789-ABCD 
+2
source
 PART1=`echo $VARIABLE | cut -d'-' -f1` 
+1
source

This might work for you:

 a="1234-123-456-890" OIFS=$IFS; IFS=-; b=($a); echo "${b[*]}"; echo "${b[@]}"; IFS=$OIFS; echo "${b[*]}" 1234-123-456-890 1234 123 456 890 1234 123 456 890 echo "${b[0]}" 1234 echo "${b[1]}" 123 echo "${b[2]}" 456 echo "${b[3]}" 890 
+1
source
  echo "abc-def-ghi"|cut -f1 -d'-' 

more about the cut

0
source

Source: https://habr.com/ru/post/1403807/


All Articles