英文:
How do I read all processes in lines, not in individual words
问题
我正在尝试在Bash中读取计算机上的所有进程,然后将它们放入日志文件中。但是,当我运行下面的代码时,每个单独的字符串都被添加到数组中,而不是整行。
processes=($(ps -o pid,comm,%mem,%cpu))
echo ${processes[@]}
这是我得到的结果:
PID COMM %MEM %CPU 538 /usr/sbin/distno 0.0 0.0 539 /usr/sbin/cfpref 0.1 0.0 556 /usr/libexec/Use 0.2 0.0 559 /usr/sbin/univer 0.2 0.0 560 /usr/libexec/kno 0.3 0.0 561 /System/Library/ 0.2 0.0
如何修改这段代码,使得processes
是整行而不是字符串的数组?
PID COMM %MEM %CPU
538 /usr/sbin/distno 0.0 0.0
539 /usr/sbin/cfpref 0.1 0.0
556 /usr/libexec/Use 0.2 0.0
559 /usr/sbin/univer 0.2 0.0
560 /usr/libexec/kno 0.3 0.0
561 /System/Library/ 0.2 0.0
我想将整个进程行读入数组,而不是每个字符串单独。
英文:
I am trying to read all processes from my computer in Bash and then put them in a log file. However, when I run the code below, each individual string is added to the array instead of the full line.
processes=($(ps -o pid,comm,%mem,%cpu))
echo ${processes[@]}
This is the result that I get
PID COMM %MEM %CPU 538 /usr/sbin/distno 0.0 0.0 539 /usr/sbin/cfpref 0.1 0.0 556 /usr/libexec/Use 0.2 0.0 559 /usr/sbin/univer 0.2 0.0 560 /usr/libexec/kno 0.3 0.0 561 /System/Library/ 0.2 0.0
How can I modify this code so that processes is an array of lines instead of strings?
PID COMM %MEM %CPU <br>
538 /usr/sbin/distno 0.0 0.0 <br>
539 /usr/sbin/cfpref 0.1 0.0 <br>
556 /usr/libexec/Use 0.2 0.0 <br>
559 /usr/sbin/univer 0.2 0.0 <br>
560 /usr/libexec/kno 0.3 0.0 <br>
561 /System/Library/ 0.2 0.0 <br>
I want to read the entire process line into array instead of each string individually
答案1
得分: 2
Use readarray
(in bash
):
readarray -t p < <(ps -o pid,comm,%mem,%cpu)
printf '%s\n' "${p[@]}"
edit (for bash < 4)
IFS=$'\n' read -r -d '' -a p < <(ps -o pid,comm,%mem,%cpu)
printf '%s\n' "${p[@]}"
英文:
Use readarray
(in bash
):
readarray -t p < <(ps -o pid,comm,%mem,%cpu)
printf '%s\n' "${p[@]}"
edit (for bash < 4)
IFS=$'\n' read -r -d '' -a p < <(ps -o pid,comm,%mem,%cpu)
printf '%s\n' "${p[@]}"
答案2
得分: -1
请按照以下方式操作:
processes=($(ps -o pid,comm,%mem,%cpu))
echo ${processes[@]} | awk '{ for(i=1;i<NF;i++)if(i%4==0){$i=$i"\n"} }1'
英文:
Do as follow:
processes=($(ps -o pid,comm,%mem,%cpu))
echo ${processes[@]} | awk '{ for(i=1;i<NF;i++)if(i%4==0){$i=$i"\n"} }1'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论