Create an array from grep generated list


I have a list of streams stored in a file. I can get the stream name using 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 will need to manipulate the outputs of this list, I will need to store these lines in an array. I found several examples offering this approach:

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

However, if I scan the array, I do not 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 return is messing with my array assignment. Any help how to fix this? Thank!

+4
source share
2 answers

This is the antipattern to fill the array! in addition, the keyword is exportmost likely incorrect. Instead, use a loop or mapfile:

Using a loop:

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

mapfile ( Bash ≥4):

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

, grep , .

mapfile :

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

Source: https://habr.com/ru/post/1665130/


All Articles