开发者

Shell read from cat line by line into array

开发者 https://www.devze.com 2023-01-24 23:24 出处:网络
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:

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


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.


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


Try

boxes=(`mycommand list | xargs`)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号