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 !
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With