7

I have one csv file that is looking like this

NameColumn1;NameColumn2;NameColumn3;NameColumn4
Row1;Row1;Row1;Row1;
Row2;Row2;Row2;Row2;
Row3;Row3;Row3;Row3;

I want to take the values in Row1, Row2 and Row3 from NameColumn1 and put them into array,the same for NameColumn2,NameColumn3 and NameColumn4.

I don't know how much rows I will have but I know the number of columns. Any help?

Thank you.

2
  • Golden - take at look at :stackoverflow.com/questions/3017128/… Commented May 11, 2016 at 21:44
  • I am beginner so I don't understand much .... help. Commented May 11, 2016 at 22:57

3 Answers 3

9

With the -a option/flag from the builtin read.

#!/usr/bin/env bash

while IFS=';' read -ra array; do
  ar1+=("${array[0]}")
  ar2+=("${array[1]}")
  ar3+=("${array[2]}")
  ar4+=("${array[3]}")
done < file.csv                                                       

printf '%s\n' "${ar1[@]}" "${ar2[@]}" "${ar3[@]}" "${ar4[@]}"
  • Just need to remember that index of an array starts counting at zero.
  • The only advantage of this solution is that you don't need a variable to assign each field.
Sign up to request clarification or add additional context in comments.

Comments

6

Assuming you have four columns

 while read a b c d; do 
   ar1+=($a)
   ar2+=($b)
   ar3+=($c)
   ar4+=($d)
done < <(sed 's/;/\t/g' somefile.txt)

You then have 4x arrays called ar1 through ar4 with the column values in them.

4 Comments

@DavidC.Rankin I don't think this works, -d makes read stop when encountering the delimiter. I'd say it would have to be IFS=';'.
@BenjaminW. there's no -d, it's 4 variables named a b c and d. It works, I ran it on a file I had sitting around before I posted it.
@SaintHax Absolutely - I commented on David's comment, which, by now, is gone - it contained an alternative to using sed with read -d, but it wouldn't have worked, which I pointed out.
@DavidC.Rankin But 100% support from me for a pure Bash solution ;)
2

Using @SaintHax answer and a tweak; this worked for my application and similarly formatted data. Note the addition of quotes on stored vars, and the removal of the sed command on the redirected file. Removed IFS settings, thanks to @Jetchisel 's comment.

while read -r a b c d; do 
    ar1+=("$a")
    ar2+=("$b") 
    ar3+=("$c") 
    ar4+=("$d") 
done < somefile.csv 

1 Comment

while IFS=';' read .... the OLDIFS trick is not needed since the IFS=';' dies/discarded after the loop is done.

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.