加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

bash – 从grep生成的列表中创建数组

发布时间:2020-12-15 22:11:10 所属栏目:安全 来源:网络整理
导读:我有一个存储在文件中的线程列表.我可以用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_pri
我有一个存储在文件中的线程列表.我可以用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]
. . .

由于我需要操作此列表的输出,我需要将这些行存储在Array中.
我发现了一些建议这种方法的例子:

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

但是,如果我浏览数组,我的早期grep没有得到相同的结果:

$printf '%sn' "${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]

似乎回车正在弄乱我的阵列分配.
任何帮助如何解决它?
谢谢 !

解决方法

这是一个填充数组的反模式!而且,export关键字很可能是错误的.改为使用循环或mapfile:

循环:

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读