Reputation: 153
I need to add two numbers to a positional argument $1 with a dash between them i.e. "15-20". It is an interval from 15 to 20 and it has to be a one positional parameter. I did this:
#!/bin/sh
a=$(echo "$1" | sed 's/-/ /g')
echo $a
It prints: 15 20 I will need this in the future as an interval so I have to take each of these numbers as a seperate variables. Instead of a = 15 20, it should be a = 15 and b = 20. How can I achieve this?
Upvotes: 3
Views: 45
Reputation: 786291
Using bash
you can use process substitution:
read a b < <(echo "$1" | sed 's/-/ /g')
# and check values
declare -p a b
declare -- a="15"
declare -- b="20"
As the helpful comment from @chepner below, you don't even need sed
. You can use read both variables using a custom IFS
:
IFS=- read a b <<< "$1"
Upvotes: 3
Reputation: 532418
With /bin/sh
, use read
and a here document.
IFS=- read a b <<EOF
$1
EOF
Or, use parameter expansion twice to drop the prefix/suffix.
a=${1%-*}
b=${1#*-}
Upvotes: 4