a06e
a06e

Reputation: 20774

Parse two integers in a string and assign them to two bash variables?

I have a program that returns two non-negative integers, as a string separated by a space. I need to run this program inside a bash script, and I need to assign the output integers to two variables $i and $j.

For definiteness, suppose I ran the program inside the script and stored its output in a variable $out, so that $out contains a string such as 56 2. Now I need to parse $out somehow to end with the integers assigned to i and j respectively. How can I do this?

Upvotes: 1

Views: 278

Answers (2)

John1024
John1024

Reputation: 113814

To assign the values in out to the variables i and j, all you need is a read statement:

$ out="56 2"
$ read i j <<<"$out"
$ echo i=$i j=$j
i=56 j=2

The <<< signifies that the read statement should take its stdin from the Here string specified by the variable out.

Reading two variables directly from a command

For specificity, let's suppose that the command is date and we want to read the hour and minute:

$ date +'%H %M'
15 45

To get those into variables, use:

$ read i j < <(date +'%H %M')
$ echo i=$i j=$j
i=15 j=45

The syntax above is a bit tricky. The construct <(...) makes the output of a program into a file-like object. (This is called "process substitution.") In this case the program is date +'%H %M'. In order to tell read to read its input (stdin) from that file-like object, we use redirection, signified by <. Thus < <(...) says to take stdin from the output of the command in parens.

The space between < and <(...) is essential. That is because << means something else entirely: it indicates the start of a Here document. So, keep the space.

Upvotes: 4

InfectedPacket
InfectedPacket

Reputation: 274

A solution I could propose you is to use the cut program within Linux. This tool is included in every distribution. Basically it would look like this:

$out = program
$i = echo $out | cut -d" " -f1
$j = echo $out | cut -d" " -f2

The parameter -d" " specifies to divide your string using the space character, the -fX specify to return the X column. So for example,

$out = "56 2"
echo "56 2" | cut -d" " -f1
>56

Upvotes: -1

Related Questions