0

Before I go on a mission to write some code, I was hoping someone could confirm the following is possible (or at least fairly simple) to do.

I am wanting to read a file containing numbers that are in 9 columns (separated by a single space) and many rows. The second column is ordered numerically, from largest to smaller. I want to discard all rows that contain below a specified number in this second column and then generate a new file and output just the top rows that conform to this rule.

Additionally, I would like to add a 10th column that is the result of a calculation between 2 other columns.

Is this done using arrays?

Many thanks in advance.

  • 2
    Why not use Excel or OpenOffice? – DigitalGhost Aug 28 '12 at 15:55
  • Anything is possible in C. You should have a go at implementing it, and post back here if you come across any specific problems. As it stands, your question is too vague for anyone to be able to provide much meaningful help. – Graham Borland Aug 28 '12 at 15:55
  • @GrahamBorland - this is not true, get my boyfriend to work properly then I agree. – Ed Heal Aug 28 '12 at 16:26

2 Answers2

1

This is trivial in awk. Suppose $N is a shell variable that contains the minimum value you want from the second column, and you want to make column 10 the sum of columns 3 and 5:

awk '$2 > '$N'{ $10 = $3 + $5 }1' input-file

This outputs all of the rows. Pipe the output to head to reduce the number of lines output, or add a counter in the awk script. If you write C code to do this, you are wasting your time unless it is an exercise to help learn C.

On the other hand, it's pretty straightforward in C. For simplicity, assume you only have 2 columns:

int c[2];
do { 
  rc = scanf( "%d %d", c, c + 1 );
  if( c[1] > N && rc == 2 )
    printf( "%d %d %d", c[0], c[1], c[0] + c[1] );
} while( rc > 0 );
William Pursell
  • 204,365
  • 48
  • 270
  • 300
0

The most strait-forward approach is probably to convert each column within the file into an array, then manipulate it as you describe from there.

Keep in mind, the file stores characters not integers, make sure you allocate your arrays accordingly to what you desire to store.

You may also find this question discussing the conversion of characters to integers useful.

Community
  • 1
  • 1
rudolph9
  • 8,021
  • 9
  • 50
  • 80