2

I use sed with <<< and read to assign all words in a string to variables. What I do is:

read -a A0 <<< $(sed '2q;d' /proc/stat)

Hence, sed reads the second line of the file file and immediately quits. The line sed has read in is fed to <<< which does expands the input it receives from sed and read -a assign the resulting values of <<< to elements of an array. Is the usage of <<< and sed in this way a good idea or are there obvious reasons that speak against this and most of all, is there a faster way to do this?

0

2 Answers 2

3

You can use array assignment directly:

A0=($(sed '2q;d' /proc/stat))

Beware that this performs globbing: if the output of the command contains shell wildcards, then the words containing wildcards are replaced by the list of matching files if there are any. If the output of the command might contain one of the characters \[?*, temporarily turn off globbing:

set -f
A0=($(sed '2q;d' /proc/stat))
set +f

This can be tiny faster than using read:

$ time for i in {1..1000}; do read -a A0 <<< $(sed '2q;d' /proc/stat); done

real    0m2.829s
user    0m0.220s
sys     0m0.480s

$ time for i in {1..1000}; do A0=($(sed '2q;d' /proc/stat)); done

real    0m2.388s
user    0m0.128s
sys     0m0.276s

With bash 4.0 and above, you can use mapfile:

mapfile -t < <(sed '2q;d' /proc/stat)

But mapfile seems to be slowest:

$ time for i in {1..1000}; do mapfile -t < <(sed '2q;d' /proc/stat); done

real    0m3.990s
user    0m0.104s
sys     0m0.444s
2
  • Asking a personal opinion here but only in a comment: Would you use array assignment directly or rather mapfile? (Why did I not think of direct array assignment???) Commented Sep 2, 2014 at 14:30
  • @lord.garbage: I will use direct assignment, see my updated.
    – cuonglm
    Commented Sep 2, 2014 at 14:32
0

The syntax seems too complex to my eyes. I'd use the following instead:

read -a A0 < <( sed '2q;d' /proc/stat )

I usually use the <<< word syntax when I need a command to take input from a variable, not from another command.

2
  • Gives me only an error so far. Commented Sep 2, 2014 at 14:20
  • @lord.garbage: Sorry, missing character. Fixed now.
    – choroba
    Commented Sep 2, 2014 at 14:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .