1

I want to add the elements of the fourth column in each line of the file to an array, but now I don't know how to add the separated elements to another array. My approach seems to have some problems:

#!/bin/bash
declare -a arr
cat 2.csv | while read line
do
    IFS=',' read -ra str <<< "$line"
    # echo ${str[3]}
    arr+=(${str[3]})
done

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

3 Answers 3

2

The problem is that each process in a pipeline operates inside a subshell. Thus, this code modifies arr inside a subshell. No change to the environment survives outside the subshell.

cat 2.csv | while read line
do
    IFS=',' read -ra str <<< "$line"
    # echo ${str[3]}
    arr+=(${str[3]})
done

To avoid that, use redirection:

while read line
do
    IFS=',' read -ra str <<< "$line"
    # echo ${str[3]}
    arr+=(${str[3]})
done <2.csv
Sign up to request clarification or add additional context in comments.

Comments

2

In addition to John1024's answer, there's no need to read the line, and the read it again to split it. You can do the splitting the first time:

while IFS=, read -ra str
do
  arr+=("${str[3]}")  # Quote here if you don't want further splitting
done < 2.csc

Comments

1

Instead of reading into an a array, you could read into variables and throw away those you don't need:

while IFS=, read -r _ _ _ str _; do arr+=("$str"); done < 2.csv

This is only practical if the index you want is relatively low, though.

Another option, using cut and process substitution:

readarray -t arr < <(cut -d, -f4 2.csv)

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.