-1

I have multiply files, each with three columns. I would like to monitor where a given column entries first change sign (i.e negative to positive) so that I save that row where this first happens to another file. In the example below, i want to monitor the change in sign in the first column.

-1 2 4  
-4 3 5  
-2 4 6
1  2 4  
2  4 5    
2  3 4      
-4 5 6  
-3 4 6  

The code should save the line -2 4 6 to another file.

  • You only care about the first column's sign change? – Jeff Schaller Mar 22 at 11:09
  • Yes only first column sign and then get the row – user343085 Mar 22 at 11:10
1

If the change is always from negative to positive non-negative, this should do. It just prints the previous line and exits when it sees a non-negative value in field 1 (change the number in $1 to look at another field):

$ awk '$1 >= 0 { print prev; exit; } { prev = $0; }' < inputfile
-2 4 6

If the change can be either way, we'll need to store the sign on the previous line and compare against that (here, the field number is required in two places, so it's taken from the variable set by -vfield=1):

$ awk -vfield=1 'function sign(x) { if (x < 0) return -1; return +1; }
      NR != 1 && sign($field) != prevsign { print prevline; exit; }
      { prevline = $0; prevsign = sign($field) }' < inputfile

In both cases, you can of course use > outputfile to redirect the output to another file.

  • "thank you". That fixes my issue :) – user343085 Mar 22 at 11:17

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.