如何以行为单位读取所有进程,而不是逐个单词。

huangapple go评论48阅读模式
英文:

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 &lt; &lt;(ps -o pid,comm,%mem,%cpu)
printf &#39;%s\n&#39; &quot;${p[@]}&quot;

edit (for bash < 4)

IFS=$&#39;\n&#39; read -r -d &#39;&#39; -a p &lt; &lt;(ps -o pid,comm,%mem,%cpu)
printf &#39;%s\n&#39; &quot;${p[@]}&quot;

答案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 &#39;{ for(i=1;i&lt;NF;i++)if(i%4==0){$i=$i&quot;\n&quot;} }1&#39;

huangapple
  • 本文由 发表于 2023年3月21日 01:52:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75793675-3.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定