linux - Bash 将 awk 的输出捕获到数组中

标签 linux arrays bash

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

我的例子:

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

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

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' 不会做任何事情并保留我的原始输出。我需要做哪些更改才能完成这项工作?

最佳答案

添加额外的括号,如下所示:

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 — Arrays .

关于linux - Bash 将 awk 的输出捕获到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15105135/

相关文章:

python - 从数组列表中查找唯一代表(元素)的列表

java - 如何使用java将字符串数组或整数值从一个类传递到另一个类?

linux - 使用 formail 获取电子邮件文件的最后一封电子邮件

android - 无法使用错误 : There's another emulator instance running with the current AVD 启动 android 模拟器

php - 在 Linux 中终止 php 浏览器请求

linux - 如何在 Linux 中更改文本文件扩展名类型?

c - 索引运算符绑定(bind)到字符串文字

linux - 如何 'grep'连续流?

linux - 超时后,杀死该进程及其所有子进程

java - Java 8 中的默认最大 Codecache 大小是多少