Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative to readarray, because it does not work on mac os x

Tags:

bash

macos

awk

perl

I have a varsValues.txt file

cat varsValues.txt
aa=13.7
something=20.6
countries=205
world=1
languages=2014
people=7.2
oceans=3.4

And I would like to create 2 arrays, vars and values. It should contain

echo ${vars[@]}
aa something countries world languages people oceans

echo ${values[@]}
13.7 20.6 205 1 2014 7.2 3.4

I use

Npars=7

readarray -t vars < <(cut -d '=' -f1 varsValues.txt)
readarray -t values < <(cut -d '=' -f2 varsValues.txt)

for (( yy=0; yy<$Npars; yy++ )); do
eval ${vars[$yy]}=${values[$yy]}
done

echo $people
7.2

But I would like it without readarray which does not work on Mac (os x) and IFS (interfield separater).

Any other solution? awk? perl? which I can use in my bash script.

Thanks.

like image 441
user3652962 Avatar asked May 24 '14 07:05

user3652962


4 Answers

You can use declare builtin:

declare -a vars=( $(cut -d '=' -f1 varsValues.txt) )
declare -a values=( $(cut -d '=' -f2 varsValues.txt) )

Although, as commenters have pointed out declare -a is superfluous.

vars=( $(cut -d '=' -f1 varsValues.txt) )
values=( $(cut -d '=' -f2 varsValues.txt) )

Works just as well.

like image 86
anubhava Avatar answered Nov 14 '22 01:11

anubhava


You could use a read loop.

while IFS=\= read var value; do
    vars+=($var)
    values+=($value)
done < VarsValues.txt
like image 26
John B Avatar answered Nov 14 '22 00:11

John B


Here's the awk version. Note that NPars is not hardcoded.

vars=($(awk -F= '{print $1}' varsValues.txt))
values=($(awk -F= '{print $2}' varsValues.txt))

Npars=${#vars[@]}

for ((i=0; i<$Npars; i++)); do
    eval ${vars[$i]}=${values[$i]}
done

echo $people
like image 7
S. Ahn Avatar answered Nov 14 '22 02:11

S. Ahn


Try:

IFS=$'\n' vars=($(cut -d '=' -f1 varsValues.txt))
IFS=$'\n' values=($(cut -d '=' -f2 varsValues.txt))
like image 3
Noel Yap Avatar answered Nov 14 '22 01:11

Noel Yap