By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,678 Members | 1,158 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,678 IT Pros & Developers. It's quick & easy.

Extract a column of data using perl

P: 1
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
Share this Question
Share on Google+
1 Reply


P: 61
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.