Andrew Landry
Andrew Landry

Reputation: 69

How to assign specific line from another file to a variable in bash

I have another file that has 2 numerical values...

22

35

I want to read those values and assign each to a variable.

There will only ever be two values, so a loop shouldn't be necessary.

I found ways to get the value line by line, but I'm unsure how to save those values to a variable that I can use in my main script.

Upvotes: 0

Views: 182

Answers (3)

glenn jackman
glenn jackman

Reputation: 246744

With bash 4, you can read the lines into an array

mapfile -t numbers < file
echo ${numbers[0]} ${numbers[1]}

Upvotes: 0

John1024
John1024

Reputation: 113814

Another way to read two lines in succession is:

{ read var1 ; read var2 ; } <data

Upvotes: 3

anubhava
anubhava

Reputation: 784898

You can use:

read a b < <(egrep -o '[0-9]+' file|tr '\n' ' ')

Upvotes: 0

Related Questions