user1950349 user1950349 - 1 year ago 115
Bash Question

split a string on a - delimiter in bash?

How do I split a string basis on a delimiter in Bash?

I have string stored in a variable as shown below:


Now I would like to split above string on
delimiter and store two numbers in two different variables.


If NUMBER1 and NUMBER2 is an empty string and not a number then exit out of the script with non zero status code.

Answer Source
IFS=- read -r number1 number2 _ <<<"$DATA"
[[ $number1 && $number2 ]] || { echo "Initial columns not read" >&2; exit 1; }
[[ $number1$number2 = *[![:digit:]]* ]] && { echo "Values are not numeric" >&2; exit 1; }

echo "Number 1 is $number1"
echo "Number 2 is $number2"

Setting IFS to your delimiter on the same line as the read command (with no separator such as ; between) scopes it to that single read operation, so it won't modify the shell's behavior elsewhere in the script.

Note the _ as an extra argument to read -- the rest of the line is stored there, preventing it from being appended to number2.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download