Alexey Kamenskiy
Alexey Kamenskiy

Reputation: 2948

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

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

I need to extract those numbers in separate variables to be able manipulate them. I tried to look at regular expressions but couldnt see any solution (or i am just blind enough not to notice.

Ideally 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 am quite new to shell scripting so i might have missed something.

Upvotes: 5

Views: 16903

Answers (5)

Rony
Rony

Reputation: 1734

/bin/sh is dash (see section "Parameter Expansion")

#!/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

Upvotes: 6

potong
potong

Reputation: 58568

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

Upvotes: 1

Balaswamy Vaddeman
Balaswamy Vaddeman

Reputation: 8540

 echo "abc-def-ghi"|cut -f1 -d'-'

more about cut

Upvotes: 0

FatalError
FatalError

Reputation: 54621

Using bash you could use an array like this:

#!/bin/bash
VARIABLE=1234-123-456-890

PART=(${VARIABLE//-/ })

echo ${PART[0]}-${PART[1]}-${PART[2]}-${PART[3]}

The ${VARIABLE//-/ } expansion changes all - to spaces and then it's split on word boundaries into an array.

Alternatively, you could 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 could change it slightly 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

Caveat: this was only tested with bash running in sh mode.

Upvotes: 14

peon
peon

Reputation: 1883

PART1=`echo $VARIABLE | cut -d'-' -f1`

Upvotes: 1

Related Questions