LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   printing column wise (http://www.linuxquestions.org/questions/programming-9/printing-column-wise-669168/)

bharatbsharma 09-11-2008 05:47 AM

printing column wise
 
Hi Friends,

I have a log file as below


siteid = HYD
spc = 100
rset = RS_D_M
siteid = DEL
spc = 200
rset = RS_K_L
siteid = DEL2
spc = 210
rset = RS_D_M


Now I need a output file where i can print column wise as below.

siteid SPC rset
HYD 100 RS_D_M
DEL 200 RS_K_L

Can anybody help me.

Is awk suitable for this

matthewg42 09-11-2008 08:23 AM

I'd probably use a little Perl program. This works, but it's not very elegant:

Code:

#!/usr/bin/perl

print "siteid SPC rset\n";

my %data;

clear_data();

while(<>) {
        chomp;
        if ( /^(siteid|spc|rset) = (.*)/ ) {

                if (defined($data{$1})) {
                        warn "at line $. - $1 found, but we still didn't print the previous record\n";
                }

                $data{$1} = $2;

                if ($1 eq "rset") {
                        if (!defined($data{'siteid'}) || !defined($data{'spc'})) {
                                warn "at line $.  - missing a siteid or spc\n";
                        }
                        print_record();
                        clear_data();
                }
        }
}

sub clear_data {
        foreach my $k (qw(siteid spc rset)) {
                delete $data{$k};
        }
}

sub print_record {
        printf "%s %s %s\n", $data{'siteid'}, $data{'spc'}, $data{'rset'};
}


chrism01 09-11-2008 08:30 AM

Code:

IFS="
"
echo "siteid SPC rset" >t1.t
for rec in `cat t.t`
do
    field=`echo $rec|cut -d' ' -f1`
    value=`echo $rec|cut -d' ' -f3`
    echo $field $value
    if [[ $field == "rset" ]]
    then
        echo -n $value >> t1.t
        echo >> t1.t
    else
        echo -n "$value " >> t1.t
    fi
done


vikas027 09-11-2008 09:00 AM

I have one more solution.

Suppose your file name is abc

Run this

Code:

cat abc | tr '=' ' ' | awk '{print $1}' | head -3 | tr '\n' ' ' > file1
echo -e -n "\n" >> file1
cat abc | tr '=' ' ' | awk '{print $2}' | tr '\n' ' ' > file2
echo -e -n "\n" >> file2

Now, You have two files as

file1
Code:

siteid spc rset
file2
Code:

HYD 100 RS_D_M DEL 200 RS_K_L DEL2 210 RS_D_M
Now, I want to insert a new line into every 3rd column, so that file2 breaks as :-
Code:

HYD 100 RS_D_M
DEL 200 RS_K_L
DEL2 210 RS_D_M

Pls someone suggest for this step, I am sure on line awk or sed could help this BUT I am not very sure how to use it.

Thanks N Regards,
VIKAS

radoulov 09-11-2008 11:00 AM

For fixed ordered columns:

Code:

awk 'BEGIN {
  OFS="\t"; FS="= *"
  print "siteid", "spc", "rset"
  }
(ORS = NR % 3 ? OFS : RS) && $0 = $2
'  filename



All times are GMT -5. The time now is 02:16 AM.