0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

0

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 '

8 Comments

I'm having the same problem reading in filenames with spaces using find, how can I fix that?
I guess $3=="task" instead of $4.
@JohnLotacs, "There are tabs between columns, only spaces in column 3." makes no sense at all, spaces are between columns
This doesn't solve my problem, this is returning just the integer, I need the whole string, "task 3" "task 2" ... "baller"
the file is TAB separated, cut -f3 ~/.todo/data returns a column of strings "task 3\ntask 2\ntask 1\nballer", I want each line inside the bash array. I edited my question to be more specific.
|

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.