469,331 Members | 1,901 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,331 developers. It's quick & easy.

Extract a column of data using perl

Hello i am extememly new to PERL and have a very basic question.

Say i have two columns in a text file something like this...

5330 1
5380 5
5390 6
5400 9
5410 11
5420 15
5430 23
5440 38
5450 57
5460 86
5470 111
5480 171
5490 226
5500 347

how do i extract just the first column and write to another file? is there an easy way to do that? i hae about 100 text files and need to extract the first column of each text file and write it to one big file (appending each time).. Any help is appreciated!!!!
Sep 15 '06 #1
1 11244
In two ways you can solve this problem.

Fisrt one is.......

1. Open each file
2. Read line by line and use the split function to separate the words and then write the necessary word into the final file.

@arr_file=("file1","file2","file3");

open(FINAL, ">result.txt");

foreach $file in @arr_file
{
open(FILE, $file);

while(defined($line=<FILE>))
{
@arr_words=split(/\s+/,$line);

print FINAL $arr[0];
}

close FILE;
}

close FINAL;

Second one is.......

Use the cut command of linux on each file and then redirect the output to the final file.


@arr_file=("file1","file2","file3");

system("touch result.txt");

foreach $file in @arr_file
{
system(" cut -d' ' -f1 $file >> result.txt");
}
Sep 16 '06 #2

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

3 posts views Thread by Phong Ho | last post: by
10 posts views Thread by mark4 | last post: by
1 post views Thread by Ori | last post: by
9 posts views Thread by Brian Hanson | last post: by
3 posts views Thread by SteveB | last post: by
1 post views Thread by CARIGAR | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.