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

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

How do I read all processes in lines, not in individual words

问题

Sure, here is the translation of the code part you provided:

我正在尝试在Bash中从我的计算机读取所有进程,然后将它们放入日志文件中。但是,当我运行下面的代码时,每个单独的字符串都被添加到数组中,而不是整行。

```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 <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 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-2.html
匿名

发表评论

匿名网友

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

确定