469,271 Members | 1,000 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

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

Counting columns in file

I have a data file which has not fixed coulmns as follows:

Column11 Column12 Column13
Column21 Column22
Column31 Column32 Column33 Column34

I want to know what is the maximum number of columns in each raw and I want to fill all the other missing columns with "NONE" to make my file with fixed column numbers so I can use it in MATLAB.

Thanks alot
Sep 23 '07 #1
5 7167
4,059 Expert 2GB
What have you tried so far?
Sep 23 '07 #2
I'm still new in perl. I only can count raws by spliting each line but so far I don't know how to deal with columns especially that I don't know how many are they in each raw. This code only give me the total raws in the file not the column.

Expand|Select|Wrap|Line Numbers
  1. my $COLUMN;
  2. my $MaxColumn;
  4. open (IN, 'c:\database.txt'); 
  5. while (<IN>) { 
  6.    chomp($line = $_);
  7.     @COLUMN = split(/\t/,$line); # split tab 
  8. $MaxColumn++;
  9. }
  10. printf "Total = $MaxColumn \n";
I wish that anyone can help me.
Sep 24 '07 #3
4,059 Expert 2GB
The length of the array is the number of columns:

@COLUMN = split(/\t/,$line); # split tab
print "There are ", scalar @COLUMN, " columns in this line";

Did you need each row in the file to have the same number of columns?
Sep 24 '07 #4
thank you very much. I added this line:
and it works very fine. Thanks really.

Now I need also to make every raw with the same number of columns by adding (-1) or (NONE) for the new columns without affecting the original data in each existed column.

I'm really thankful
Sep 24 '07 #5
I think I solved it by adding these lines:

Expand|Select|Wrap|Line Numbers
  1. open(TARGET,"> new.txt"); 
  2. while ($size < $MaxColumn) { 
  3.        $COLUMN[$size] = -1;
  4. $line = join("\t",@COLUMN);
  5. $size++;
  7.   }
  8. print TARGET $line ."\n";
Thank you alot for helping.
Sep 24 '07 #6

Post your reply

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

Similar topics

6 posts views Thread by John Reese | last post: by
68 posts views Thread by Martin Joergensen | last post: by
2 posts views Thread by justin | last post: by
2 posts views Thread by =?ISO-8859-2?Q?Gregor_Kova=E8?= | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.