0

i need help. i have this file i want read it line by line with for loops and delete the line less than 20% the number will with list %CPU .

%CPU PID USER UID COMMAND %MEM 71 9136 ashti 1000 firefox 4.6 36 1432 ashti 1000 gnome-shell 8.6 25 9100 ashti 1000 gedit 1.1 3 9092 ashti 1000 nautilus 1.2 2 9109 ashti 1000 gnome-terminal- 0.9 1 1248 ashti 1000 Xorg 2.6 0 1375 ashti 1000 VBoxClient 0.0 0 9118 ashti 1000 bash 0.1 0 269 root 0 systemd-journal 2.8 

i want be like this example

%CPU PID USER UID COMMAND %MEM 71 9136 ashti 1000 firefox 4.6 36 1432 ashti 1000 gnome-shell 8.6 25 9100 ashti 1000 gedit 1.1 

and save in new file .

best regards

4
  • why are you requiring the use of a for loop? Commented Oct 29, 2019 at 18:01
  • is this a school assignment? Commented Oct 29, 2019 at 18:02
  • please check this link its my code question [link] (unix.stackexchange.com/questions/549368/…) Commented Oct 29, 2019 at 20:01
  • If you are using Ubuntu you can post these questions in Ask Ubuntu What command did you use to generate the CPU%? It appears like it needs to be divided by the number of CPU cores for an accurate percentage. Commented Oct 30, 2019 at 0:09

3 Answers 3

2

With grep:

grep -e "^%" -e "^[2-9][1-9]" file | column -t 

column -t to make it pretty:

%CPU PID USER UID COMMAND %MEM 71 9136 ashti 1000 firefox 4.6 36 1432 ashti 1000 gnome-shell 8.6 25 9100 ashti 1000 gedit 1.1 
1

With retaining header, awk expression:

$ awk 'NR==1 || (NR > 1 && $1 > 20)' file %CPU PID USER UID COMMAND %MEM 71 9136 ashti 1000 firefox 4.6 36 1432 ashti 1000 gnome-shell 8.6 25 9100 ashti 1000 gedit 1.1 
1
0

A for loop is not a good choice for this task - for a discussion of the reasons why, see for example

My personal choice would be Miller:

$ mlr --pprint filter -x '${%CPU} < 20' file > newfile $ cat newfile %CPU PID USER UID COMMAND %MEM 71 9136 ashti 1000 firefox 4.6 36 1432 ashti 1000 gnome-shell 8.6 25 9100 ashti 1000 gedit 1.1 
1

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.