0

I am not used to code, but for my work I have to do some processing with text-files and I need some help with a problem I encountered.

I have a file with two columns containing some numbers:

180.000000   115.944480
180.000000    95.979157 
180.000000    93.583322 
178.593750   122.797168 
178.593750   120.000000 
178.593750   117.279613 
178.593750   102.024699 
178.593750    99.594068
   ...           ...

There are several values in the second column associated with one unique value in the first column. Now I want to print for every unique value in column 1 the interval of values in column 2.

Desired output:

115.944480 93.583322
122.797168 99.594068
...

Obviously I have to store the values and have to print a previous and the recent value of column 2 if the value in column 1 changes. But that is the problem: How can this be realized in bash or awk?

  • Please add a description of whatever progress you have made for yourself in either awk or bash. You should make a minimal effort rather than expecting helpful people doing all the work for you. – Claus Andersen Apr 23 '18 at 8:17
0

Awk solution for your initial condition "for every unique value in column 1 the interval of values in column 2" (as you have changed your condition considerably):

awk 'NR > 1{ 
         if ($1 == num1) intvl += num2 - $2;
         else { print intvl; intvl = 0 }
    }
    { num1 = $1; num2 = $2 }
    END{ print intvl }' file

Sample output:

22.3612
23.2031

Covering the 2nd condition "to print a previous and the recent value of column 2 if the value in column 1 changes":

awk '!a[$1]++{ 
         if (first != "") { print first, last; first = last = "" }
         first = $2
     }
     { last = $2 }
     END{ print first, last }' file

The output:

115.944480 93.583322
122.797168 99.594068
  • Thank you very much! It works very well for my purpose! Some question about the syntax for my understanding: What does the !a[$1]++ and the != "" mean? – quadrupoltensor Apr 23 '18 at 9:12
  • @quadrupoltensor, 1) !a[$1]++ gives true on the 1st occurrence of the 1st field value $1. 2) !="" means "is not equal to empty string" – RomanPerekhrest Apr 23 '18 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.