Bash arrays: need help with a space

I am trying to create an array from bash from a file with the following sample:

data, data, interesting
data, data, more interesting

Array Fill Method:

read -r -a DATA1 <<< $(cat $FILE | awk -F, '{ print $1 }')
read -r -a DATA2 <<< $(cat $FILE | awk -F, '{ print $2 }')
read -r -a DATA3 <<< $(cat $FILE | awk -F, '{ print $3 }')

When I examine the DATA3 array, there are 3 elements:

interesting
more
interesting

I need it to display only two elements:

interesting
more interesting

How can I save a space in field 3, so when I call this element from an array, it looks like "more interesting"? Is there a better way to handle this?

+3
source share
4 answers

The key is to use the variable IFS(internal field separators) along with read.

readcan read words directly into the array using the option -a. Set IFS=,and separate a comma:

while read f; do
    echo "$f" | (IFS=, && read -a arr && echo ${arr[2]})
done

there will be an echo

interesting
 more interesting 

:

IFS=, && read f1 f2 f2

EDIT: Bash Scripting Guide.

+3

cut. :

read -r -a DATA1 <<< $(cut -d, -f 1 $FILE)
read -r -a DATA2 <<< $(cut -d, -f 2 $FILE)
read -r -a DATA3 <<< $(cut -d, -f 3 $FILE)
+1
IFS=','
while read -a array
do
    echo "${array[2]}" 
done < data.csv
+1
source
>> Is there a better way to handle this? - Tee Bone

$ awk -F", " '{print $3}' file
interesting
more interesting
0
source

Source: https://habr.com/ru/post/1728317/


All Articles