How can I extract a value from comma separated values ​​in Perl?

I have a log file containing statistics from different servers. I only separate statistics from this log file with a regular expression. I am trying to grab CPU usage from a running process. For SunOS, I have below:

process,10050,user1,218,59,0,1271M,1260M,sleep,58.9H,0.02%,java

Here CPU% is in the 11th field if we separate it with commas (,). This field has a% sign, which is unique, and I can use below regex. To get this value:

regex => q/^process,(?:.*?),((?:\d+)\.(?:\d+))%,java$/,

For Linux system I have below:

process,26190,user1,20,0,1236m,43m,6436,S,0.0,1.1,0:00.00,java,

Here, the CPU usage is in the 10th column, but without the% sign, and there is nothing unique in this field.

What regular expression pattern should I use to get this value?

+3
source share
5

, .. ? /^(?:[^,]+,){9}([^,]+)/' , .

+2

, split .

.

my @fields = split(/,/, $input);
+3

Text:: CSV_XS , . , . , .

Once you extract the correct position, you can cancel the% sign if it is there.

+1
source

you have a data structure that has a different delimiter, so do not use a regular expression, but simply use the division and get your element by index (or cut). This is easier.

$output="process,10050,user1,218,59,0,1271M,1260M,sleep,58.9H,0.02%,java";
@s = split /,/,$output;
print "$s[10]\n";

for linux, just get $s[9]

-1
source

I don't know anything about Linux, but just ignore the code if it looks too naive :)

 /^process.*(?<=[A-Z],)((?:\d+)\.(?:\d+)).*java$/;
-1
source

Source: https://habr.com/ru/post/1740282/


All Articles