Marry Jane
Marry Jane

Reputation: 364

Read paired arrays from a file in bash

I have a bash script which breaks bash array into pairs, and match on either element;

declare -a arr=(
    "apple" "fruit"
    "cabbage" "vegetables"
)

for ((i=0; i<${#arr[@]}; i+=2)); do
    echo "${arr[i]} ${arr[i+1]}"
done

So when you run this script, it prints out each 2 element from the array, like this;

# bash script
apple fruit
cabbage vegetables

and I can also choose any element I want with ${arr[i+@]}.

Now I'm trying to read this array from a separate text file, instead of inside the script since I'll be manipulating this array in the future.

I've tried this method so far, which looked pretty promising at first but didn't work at all;

filename='stuff.log'
filelines=`cat $filename`

for line in $filelines ; do
    props=($line)
    echo "${props[0]} ${props[1]}"
done

which should've print out the below content in the console (basically the same thing as the first script where the array is inside the script), supposedly but instead, it returned nothing.

# bash script
apple fruit
cabbage vegetables

And the inside of stuff.log is;

"apple" "fruit"
"cabbage" "vegetables"

How can I basically read the array from a separate file for the first script and also be able to manipulate the content of array file in the future?

Upvotes: 0

Views: 118

Answers (1)

KamilCuk
KamilCuk

Reputation: 141768

I think, if you trust your input, you can do:

IFS=' \n' eval props=($(<stuff.log))

Eval is evil and it is there to remove leading and trailing ". And it will parse properly elements with spaces in them. We can do a little safer by reading the file into array and then removing leading and trailing ":

IFS=' \n' props=($(<stuff.log))
IFS='\n' props=($(printf "%s\n" "${props[@]}" | sed 's/^"//;s/"$//'))

Anyway I think I would hesitate to use such method in production code. Would be better to write a proper fully parser that takes " into account and reads input char by char.

If you want to read a file into an array, use mapfile or readarray commands (they are exactly the same command).

Upvotes: 1

Related Questions