separate a variable into two using SH/BASH

I have a number I get from cat like this: "(number1,number2)" I want to split the values into two different variables.

Answers


A quick and dirty way to do it in a single line is to use grep:

read -r var1 var2 < <(grep -o '[0-9]*' file.txt)

A more robust way that does not use external programs (and hence is faster) is to use $BASH_REMATCH:

if [[ "$(<file.txt)" =~ ^\((.*),(.*)\)$ ]]; then
    var1="${BASH_REMATCH[1]}"
    var2="${BASH_REMATCH[2]}"
fi

The basic idea in this method is that we read the file contents into a string (with "$(<file.txt)") and then we immediately test that string against a regular expression (with the =~ operator). The regular expression include two capturing groups, which we later retrieve from the $BASH_REMATCH array. The regular expression extracts the groups by ignoring the ( and ) at the beginning and at the end of the string and finds the , that separates them.


Need Your Help

Custom message for geolocation

javascript jquery html5 geolocation location

I am looking for a way in which i can display a custom message when the geolocation script asks for the user to either allow or deny access to their location.

Code deleted but still outputting

c# asp.net caching

I have removed several functions from my Codebehind .aspx.cs page. However the webpages are still calling the functions even though I do not call them nor to the functions actually exist anymore.