How to read file line by line in shell script?

Hi Team,

I want to read a file line by line and print the data in multiple variables.

By using below script i am doing that but i want to increase the performance by using for loop Can someone let me know how to do that ?.

Below is my script:

ps aux  > /tmp/test
sed 1d  /tmp/test >  /tmp/test1

while IFS= read -r line;

do
USER=$(echo "$line"|awk  '{print $1}')

CPU_percentage=$(echo "$line"|awk  '{print $3}')


echo -e "{\"'PID'\":\"'"$PID"'\",\"'CPU_percentage'\":\"'"$CPU_percentage"'\"}"


done < /tmp/test1

How to use for loop for above script to get more performance from the shell script ?.

Instead of reading the input a line at a time:

read a
while read a b c d e f
do
    echo USER= $a CPU= $c
done

run as

ps aux |script_above
 

You end up only reading the output of ps once instead of multiple times.

Following along from jgt's suggestion you could try this all in one script:

ps aux | (
   # discard first (headings) line
   read a

   while read a b c rest
   do
       echo -e "{\"'PID'\":\"'"$a"'\",\"'CPU_percentage'\":\"'"$c"'\"}"
   done
)

Hi
Try this

ps --no-headers -eo "{\"'PID'\":\"'%p'\",\"'CPU_percentage'\":\"'%C'\"}"

and so on if you need add fields

1 Like