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 $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
I also tried the following:
我也尝试了以下几点:
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
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'什么都不做,并保留原来的输出。我需要做什么改变才能让这个工作?
1 个解决方案
#1
45
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
See also bash
— Arrays.
参见bash -数组。
#1
45
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
See also bash
— Arrays.
参见bash -数组。