0

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?

3
  • Do you want to store the lines of a file in an array? Or do you have a single line that you want to split into words? It's not clear what you're asking. Commented Nov 7, 2017 at 14:01
  • I want to split words to array from every line. Need something like this for every_line_in File ; do item1=$array_form_line_0[0] item2=$array_form_line_0[3] done Commented Nov 7, 2017 at 14:05
  • Do you want the line in an array, or just in item1 and item2? Commented Nov 7, 2017 at 14:11

2 Answers 2

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

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]}"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.