Bash将awk的输出捕获到数组中 [英] Bash capturing output of awk into array

查看:847
本文介绍了Bash将awk的输出捕获到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个小问题.我有一个将输出通过管道传输到awk的命令,但我想一个一个地捕获到数组的输出.

I am stuck on a little problem. I have a command which pipes output to awk but I want to capture the output of to an array one by one.

我的例子:

myarr=$(ps -u kdride | awk '{ print $1 }')

但这会将我的所有输出捕获到一个用逗号分隔的巨型字符串中:

But that capture all my output into one giant string separated by commas:

output: PID 3856 5339 6483 10448 15313 15314 15315 15316 22348 29589 29593 32657 1

我还尝试了以下方法:

IFS=","
myarr=$(ps -u kdride | awk '{ print $1"," }')

But the output is: PID, 3856, 5339, 6483, 10448, 15293, 15294, 15295, 15296, 22348, 29589, 29593, 32657,
1

我希望能够将每个pid捕获到其自己的数组元素中.设置IFS = '\n'不会执行任何操作,并保留我的原始输出.要进行这项工作,我需要做些什么改变?

I want to be able to capture each individual pid into its own array element. Setting IFS = '\n' does not do anything and retains my original output. What change do I need to do to make this work?

推荐答案

添加其他括号,如下所示:

Add additional parentheses, like this:

myarr=($(ps -u kdride | awk '{ print $1 }'))

# Now access elements of an array (change "1" to whatever you want)
echo ${myarr[1]}

# Or loop through every element in the array
for i in "${myarr[@]}"
do
   :
  echo $i
done

另请参见 bash —阵列.

See also bash — Arrays.

这篇关于Bash将awk的输出捕获到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆