LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Split string and numeric with perl (https://www.linuxquestions.org/questions/programming-9/split-string-and-numeric-with-perl-767026/)

kariagekun 11-05-2009 05:09 AM

Split string and numeric with perl
 
Hi experts,

I have a file contains this line:

Mem: 906292k total, 873656k used, 32636k free, 164852k buffers

------------
I have made a perl script to split that lines

@top_file = <JX>;

foreach my $regex (@top_file){
if ($regex =~ /Mem: (.*)$/){
@data = split(/,\s/, $regex);

the result is : 906292k total873656k used32636k free164852k buffers

My question, how to delete all string k total, k used, k free, k buffers, so I just have a number e.g. 906292 873656 32636 164852.

Many thanks for your help.

ghostdog74 11-05-2009 05:21 AM

if Perl is not a must, here's awk for you
Code:

$ awk '{for(i=2;i<=NF;i+=2)printf "%s ",$i+0}' file
906292 873656 32636 164852


syg00 11-05-2009 06:17 AM

Code:

grep -oP "\d*" ???
Yes, I know it's grep, but that "P" is to use perl style regex ... (hint maybe)

Telemachos 11-05-2009 06:37 AM

Quote:

Originally Posted by syg00 (Post 3745556)
Code:

grep -oP "\d*" ???
Yes, I know it's grep, but that "P" is to use perl style regex ... (hint maybe)

Just a note: the -P flag isn't available on many versions or builds of grep. (Also, the Perl-style regexes of grep and many other tools and libraries aren't really Perl regular expressions. That doesn't mean that they're bad or useless, but it can trip you up if you expect them to be identical to Perl's regexes.)

@kariageken: Rather than slurp the whole file in at once, I would read it in line by line. In terms of removing everything but the digits, I would do that using map as I did the split. Here's an example:
Code:

#!/usr/bin/env perl
use strict;
use warnings;

open my $fh, '<', 'file' or die "Can't open 'file' for reading: $!";

while (my $line = <$fh>) {
    if ($line =~ /^Mem:/) {
        my @data = map { s/[^0-9]//g; $_ } split(/,\s+/, $line);
        print "@data\n";
    }
}


kariagekun 11-05-2009 07:31 PM

Hai All, thank you for your reply and appreciate for your solution

Regards
Kariagekun


All times are GMT -5. The time now is 08:32 AM.