Extract all negative number from column2 in another file

Viewed 43

I have a very long data file "file.dat" with two columns. Here I am putting a very small portion. I want to extract all the negative numbers from the column2 into another file let us say file2.dat and similarly for positive numbers from the same column2 to another file file3.dat

    4.0499   -7.1787
    4.0716   -7.1778
    4.0932   -7.1778
    4.1148   -7.1785
    4.1365   -7.1799
    4.1581   -7.1819
    4.1798   -7.1843
    4.2014   -7.1868
    4.2231   -7.1890
    4.2447   -7.1902
    4.2663   -7.1900
    4.2880   -7.1886
                        <-------Note: this kind of break is also there in many places 
    0.0000    2.1372
    0.0707    2.1552
    0.1414    2.2074
    0.2121    2.2864
    0.2828    2.3791
    0.3535    2.4646
    0.4242    2.5189
    0.4949    2.5207
    0.5655    2.5098

Expected Results for Negative numbers file2.dat

 -7.1787
 -7.1778
 -7.1778
 -7.1785
 -7.1799
 -7.1819
 -7.1843
 -7.1868
 -7.1890
 -7.1902
 -7.1900
 -7.1886

Expected Results for Positive numbers file3.dat

2.1372
2.1552
2.2074
2.2864
2.3791
2.4646
2.5189
2.5207
2.5098

Nearest Solution I found

This solution did not work for me because of my lack of knowledge.

http://www.unixcl.com/2009/11/awk-extract-negative-numbers-from-file.html

2 Answers

It is quite simple to do with awk. You simply check the value in the 2nd column and write it out based on its value, e.g.

awk '$2<0 {print $2 > "negative.dat"} $2>=0 {print $2 > "positive.dat"}' file

Where the two rules used by awk above are:

  • $2<0 {print $2 > "negative.dat"}, if the value in the 2nd column is less than 0, write to negative.dat,
  • $2>=0 {print $2 > "positive.dat"}, if the value in the 2nd column is greater than or equal to 0, write to "positive.dat".

Example Use/Output

With you example data in file (without your comment), running the above would result in:

$ cat negative.dat
-7.1787
-7.1778
-7.1778
-7.1785
-7.1799
-7.1819
-7.1843
-7.1868
-7.1890
-7.1902
-7.1900
-7.1886

The positive values in:

$ cat positive.dat
2.1372
2.1552
2.2074
2.2864
2.3791
2.4646
2.5189
2.5207
2.5098

David's answer is pretty good, here is a shorter awk one liner using ternary condition:

awk 'NF>1 {print $2 > ($2 < 0 ? "neg.dat" : "pos.dat")}' file
Related