0

I am currently working with a bash script. I have a csv file where every line looks like the following:

1,ABC DEF
2,GHI JKL

I want to create an array with only values in the second field, and then print them.

My current solution is the following:

myarr=($(awk -F, '{print $2}' filename.csv))
for i in "${myarr[@]}" 
do
    echo $i
done

My output looks like this:

ABC
DEF
GHI
JKL

When I need it to look like this:

ABC DEF
GHI JKL

I need the result to be in a variable for future operations!

How do I solve this problem?

2
  • 1
    Do you need them in an array, or do you just need the output you show? Commented Apr 26, 2019 at 19:45
  • I actually need them in an array! Commented Apr 27, 2019 at 10:31

3 Answers 3

3
mapfile -t myarr < <(awk -F, '{print $2}' filename.csv)
declare -p myarr

Output:

declare -a array='([0]="ABC DEF" [1]="GHI JKL")'

See: help mapfile, help declare

Sign up to request clarification or add additional context in comments.

Comments

3

If you want values in shell array then don't use awk. Just use a loop like this:

arr=()
while IFS=, read _ val; do
   arr+=("$val")
done < file

# check array content
declare -p arr
declare -a arr='([0]="ABC DEF" [1]="GHI JKL")'

# loop through array
for i in "${arr[@]}"; do
   echo "$i"
   # or do whatever with individual element of the array
done

3 Comments

Hi, thanks for this answer. when using declare i can see the array looking the way I want it to. But when I iterate over it, using the same for loop I used before, I still get the wrong output ("ABC DEF" is printed in two separate lines).
See this answer on how to iterate an array: stackoverflow.com/a/8880633/548225 Make sure you quote it properly as shown in answer.
I have added sample code for looping though array. Let me know if there is any problem.
2

You can also simply read the entire line into the array, then strip the first field.

mapfile -t myarr < filename.csv
myarr=("${myarr[@]#*,}")

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.