Jared Aaron Loo
Jared Aaron Loo

Reputation: 678

How to store elements with whitespace in an array?

Just wondering, assuming I am storing my data in a file called BookDB.txt in the following format :

C++ for dummies:Jared:10.52:5:6 
Java for dummies:David:10.65:4:6

whereby each field is seperated by the delimeter ":".

How would I preserve whitespace in the first field and have an array with the following contents : ('C++ for dummies' 'Java for dummies')?

Any help is very much appreciated!

Upvotes: 0

Views: 134

Answers (4)

merlin2011
merlin2011

Reputation: 75585

Ploutox's solution is almost correct, but without setting IFS, you will not get the array that you seek, with two elements in this case.

Note: He corrected his solution after this post.

 IFS=$'\n': arr=( $(awk -F':' '{print $1 }' Input.txt ) )
 echo ${#arr[@]}
 echo ${arr[0]}
 echo ${arr[1]}

Output:

2
C++ for dummies
Java for dummies

Upvotes: 1

Aserre
Aserre

Reputation: 5072

I totally misunderstood your question on my 1st attempt to answer. awk seems more suited for your need though. You can get what you want with simple scripting :

IFS=$'\n' : MYARRAY=($(awk -F ":" '{print $1}' myfile))

the -F flag forces : as the field separator.

echo ${MYARRAY[0]} will print :

C++ for dummies

Upvotes: 1

Mustafa Celik
Mustafa Celik

Reputation: 2399

$ yes sed -i "s/:/\'\'/" BookDB.txt | head -n100 | bash

this command while work. this is a linux command, run it on shell in same path with BookDB.txt

Upvotes: 0

user000001
user000001

Reputation: 33357

Just use a while loop:

#!/bin/bash

# create and populate the array
a=()
while IFS=':' read -r field _
do
    a+=("$field")
done < file

# print the array contents
printf "%s\n"  "${a[@]}"

Upvotes: 1

Related Questions