John Lotacs
John Lotacs

Reputation: 1254

Storing newline separated strings into array with bash

I have the following code

tasks=$(cut ~/.todo/data -f3)

data consists of

1331956800  29  task 5
1361077200  28  task 3
1363554894  26  task 1
1363555119  30  baller

For some reason, I can extract the first two columns with this method but the third doesn't seem to work properly. I tried setting IFS='\n' before tasks= but it still refuses to work.

There are tabs between columns, only spaces in column 3.

I want

${tasks[0]} = "task 5"
${tasks[1]} = "task 3"
...
${tasks[3]} = "baller"

Here is the output of cut

$ cut ~/.todo/data -f3
task 5
task 3
task 1
baller

Upvotes: 0

Views: 1857

Answers (2)

Josh Cartwright
Josh Cartwright

Reputation: 801

Simple bash solution.

tasks=()
while IFS=$'\t' read _ _ t; do
        tasks+=("$t")                                                       
done <<-!
        1331956800      29      task 5
        1361077200      28      task 3
        1363554894      26      task 1
        1363555119      30      baller
!

for t in "${tasks[@]}"; do
        echo "$t"
done

Upvotes: 1

Gilles Qu&#233;not
Gilles Qu&#233;not

Reputation: 184985

splits columns on space or tabs by default (that can be more than just one of these) and it's more suitable for files with mixed columns delimiters.

readarray a < <(awk '{print "\047" $3, $4 "\047"}' file.txt)
for i in ${!a[@]}; do echo "index[$i]=${a[i]}"; done

Edit : your question grown in the thread, so

readarray a < <(
    awk '{$1=$2=""; sub(/^ +/, ""); print "\047" $0 "\047"}' ~/.todo/data
)

\047

is the octal ASCII representation of '

Upvotes: 0

Related Questions