4


I have a list of threads stored in a file. I can retrieve the threads name with a grep:

$ grep "#" stack.out
"MSC service thread 1-8" #20 prio=5 os_prio=0 tid=0x00007f473c045800 nid=0x7f8 waiting on condition [0x00007f4795216000]
"MSC service thread 1-7" #19 prio=5 os_prio=0 tid=0x00007f4740001000 nid=0x7f7 waiting on condition [0x00007f479531b000]
"MSC service thread 1-6" #18 prio=5 os_prio=0 tid=0x00007f4738001000 nid=0x7f4 waiting on condition [0x00007f479541c000]
. . .

As I'd need to manipulate the output of this list, I'd need to store these lines in an Array. I've found some examples suggesting this approach:

$ export my_array=( $(grep "#" stack.out) )

However if I browse through the Array I don't get the same result from my earlier grep:

$ printf '%s\n' "${my_array[@]}"

"MSC
service
thread
1-8"
#20
prio=5
os_prio=0
tid=0x00007f473c045800
nid=0x7f8
waiting
on
condition
[0x00007f4795216000]
"MSC
service
thread
1-7"
#19
prio=5
os_prio=0
tid=0x00007f4740001000
nid=0x7f7
waiting
on
condition
[0x00007f479531b000]

It seems that carriage returns are messing with my array assignment. Any help how to fix it ? Thanks !

0

2 Answers 2

5

This is an antipattern to populate an array! moreover, the export keyword is very likely wrong. Use a loop or mapfile instead:

With a loop:

my_array=()
while IFS= read -r line; do
    my_array+=( "$line" )
done < <(grep "#" stack.out)

or with mapfile (with Bash≥4):

mapfile -t my_array < <(grep "#" stack.out)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your help. Both replies were correct: I've chosen this one as you provided an additional way to do it.
5

The problem is that the output of grep is being split on all whitespace before the array is created, so every word becomes a separate element in the array.

Use mapfile to create your array instead:

mapfile -t my_array < <(grep "#" stack.out)

1 Comment

Thank you very much for the explanation

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.