mia102aim
mia102aim

Reputation: 103

How to read a columns from text file and store it in array? Bash

In text file every line include some number of words. It looks like

split time not big
every cash flu green big
numer note word
swing crash car out fly sweet

How to split those lines and store it in array? I need to do with array something like this

for i in $file

do
echo "$array[0]"
echo "$array[2]"
done

Can anyone help?

Upvotes: 0

Views: 5730

Answers (2)

melpomene
melpomene

Reputation: 85827

I don't see why you need an array, then. You could just do this:

while IFS= read -r line; do
    read -r item1 item2 item3 <<< "$line"
    printf '%s\n%s\n' "$item1" "$item3"
done < "$file"

But if you want to, you can make read give you an array, too:

    read -ra array <<< "$line"
    printf '%s\n%s\n' "${array[0]}" "${array[2]}"

Upvotes: 1

oliv
oliv

Reputation: 13259

You can read the file line by line with read and assign the line to an array. It's rather fragile and might break depending on the file content.

while read line; do 
   array=( $line )
   echo "${array[0]}"
   echo "${array[2]}"
done < file

A better way to parse text file is to use awk:

awk '{print $1; print $3}' file

Upvotes: 3

Related Questions