Bash 将 awk 的输出捕获到数组中 [英] Bash capturing output of awk into array
本文介绍了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屋!
查看全文