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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15105135/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 19:08:10  来源:igfitidea点击:

Bash capturing output of awk into array

linuxarraysbash

提问by Paul

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.

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

My example:

我的例子:

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

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

I also tried the following:

我还尝试了以下方法:

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

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

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?

我希望能够将每个单独的 pid 捕获到它自己的数组元素中。设置IFS = '\n'不做任何事情并保留我的原始输出。我需要做哪些改变才能使这项工作发挥作用?

采纳答案by kamituel

Add additional parentheses, like this:

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

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

# 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

See also bash— Arrays.

另请参阅bash- 数组

回答by jarno

Use Bash's builtin mapfile(or its synonym readarray)

使用 Bash 的内置映射文件(或其同义词readarray

mapfile -t -s 1 myarr < <(ps -u myusername | awk '{print }')

At least in GNU/Linux you can format output of ps, so no need for awkand -s 1

至少在 GNU/Linux 中你可以格式化输出ps,所以不需要awk-s 1

mapfile -t myarr < <(ps -u myusername -o pid=)