user80805
user80805

Reputation: 6508

Shell read from cat line by line into array

I have a command which outputs something like that:

lucid32
lucid64

I need to read it into array. So in this particular case I need an equivalent of:

boxes =(lucid32 lucid64)

I tried to read it like that:

boxes=(`mycommand list | tr '\n' ' '`)

but it returns $'\033'[0Klucid

How can I fix that?

UPDATED:

it looks like it didn't work because this command outputs a bunch of junk:

\r\e[0Klucid32\n\r\e[0Klucid64\n

Upvotes: 1

Views: 1949

Answers (4)

thkala
thkala

Reputation: 86333

How about this (in bash):

boxes=(); while read l; do boxes+=("$l"); done < <(mycommand list)

This will put each output line in a separate array element. While this:

boxes=(); while read l; do boxes+=("$l"); done < <(mycommand list | tr "$IFS" '\n')

will also separate elements on shell parameter delimiters. This will separate on whitespace:

boxes=(); while read l; do boxes+=("$l"); done < <(mycommand list | tr '[:space:]' '\n')

It's not as fast as some of the other solutions but you can control how to store the array elements better.

Upvotes: 1

Dennis Williamson
Dennis Williamson

Reputation: 359965

What shell? Some don't support arrays.

The "junk" you see is terminal control codes for cursor movement or text coloring, etc. It's likely a code to clear to the end of the line.

What command is outputting those characters? Some commands will automatically disable those codes when their output is going somewhere other than a tty. Others have command-line options to turn that off. There are also utilities that will strip the codes for you.

Upvotes: 1

Ole Melhus
Ole Melhus

Reputation: 1929

Try

boxes=(`mycommand list | xargs`)

Upvotes: 1

Simone
Simone

Reputation: 11797

Try with boxes=$(mycommand list | tr '\n' ' ')

Upvotes: 1

Related Questions