Monday, November 29, 2010

How to import the data into an excel sheet using Perl / Shell?

INPUT: 

%cat temp.txt

abc 123 abc@123
def  456 def@456
ghi  789 ghi@789

Perl Script:

#!/usr/bin/perl5.8.8

open FH1, "temp.txt" or die "cannot open the file $!: \n";
open FH2, ">output_file.csv" or die "cannot open file handler  $!: \n";  ###( .csv stands for comma separated variables.)
@lines=<FH1>;
foreach my $l (@lines) {

chomp($l);
@words=split(/\s+/,$l);
foreach my $w (@words) {
print FH2 "$w,";
}
print FH2 "\n";
}
close(FH1);
close(FH2);

Shell Script:

#!/bin/sh

file=`cat ./temp.txt | sed -s 's/ /,/g'`;
echo "$file" > output_file.csv;


OUTPUT: 

Open the output_file in a cvs format viewer. You can find an excel sheet with the information.

No comments:

Post a Comment