Pau*_*aul 37 linux arrays bash
我遇到了一个小问题.我有一个命令管道输出到awk但我想逐个捕获数组的输出.
我的例子:
myarr=$(ps -u kdride | awk '{ print $1 }')
Run Code Online (Sandbox Code Playgroud)
但是我将所有输出捕获到一个用逗号分隔的巨大字符串中:
output: PID 3856 5339 6483 10448 15313 15314 15315 15316 22348 29589 29593 32657 1
Run Code Online (Sandbox Code Playgroud)
我也尝试过以下方法:
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
Run Code Online (Sandbox Code Playgroud)
我希望能够将每个pid捕获到自己的数组元素中.设置IFS = '\n'
不执行任何操作并保留原始输出.我需要做些什么改变来完成这项工作?
kam*_*uel 61
添加其他括号,如下所示:
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
Run Code Online (Sandbox Code Playgroud)
另见bash
- 数组.
使用 Bash 的内置映射文件(或其同义词readarray
)
mapfile -t -s 1 myarr < <(ps -u myusername | awk '{print $1}')
Run Code Online (Sandbox Code Playgroud)
至少在 GNU/Linux 中你可以格式化 的输出ps
,所以不需要awk
和-s 1
mapfile -t myarr < <(ps -u myusername -o pid=)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
53136 次 |
最近记录: |