Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

sh

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.

like image 710
Alexey Kamenskiy Avatar asked Mar 28 '12 04:03

Alexey Kamenskiy


1 Answers

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.

like image 167
FatalError Avatar answered Sep 29 '22 16:09

FatalError