Quick Question concerning Reading and Writing

First off, this is not homework nor for any class.

I have a file (column) of data such as:

12.56
2.78
0.54
22.7
... etc.

(call the file "num") I want to read in each line, then check to see whether it's greater than or equal to a value, say "1". If it is, save it in one file, if it's not, save it in another file. So in other words, I'll end up with two files, each a column of data. Below is what I tried:

read a < num
if [ "${a}" -ge 1 ]; then 
    ${a} >> OK.txt
else
    ${a} >> BAD.txt
fi

It appears to work for the very first line, but then stops. I'm sure there's a simple way to get what I want, but I don't know how. Help, would certainly be appreciated! Thanks.

Try..

while read a 
do
  if [ "${a}" -ge 1 ]; then 
      ${a} >> OK.txt
  else
      ${a} >> BAD.txt
  fi
done < num

Thanks Ygor, that *almost* works!
The problem I get is that for some reason no values are written to OK.txt
Also, for each line that is run, I get an error similar to this:

./num.sh[26]: 1.3004: not found [No such file or directory]

so for the above value (1.3004) it does not write it to OK.txt
However, it appears to write out the values that it should to BAD.txt for some reason? I don't know if it matters, but I'm running the script in ksh. Thanks!

 nawk '{if($0>1){printf("%s\n",$0) >> "ok.txt" }else{printf("%s\n",$0) >> "bad.txt"}}' inputfile
1 Like

Thanks, it looks like it should work, but unfortunately nawk does not work, since I get:

-bash: nawk: command not found

... so, if possible it would be great to get the code Ygor started on working.

---------- Post updated at 02:26 AM ---------- Previous update was at 02:24 AM ----------

Of course, if I just run it in awk instead of nawk it appears to work :slight_smile:

If possible, I would still love to know why the code Ygor gave does not work? Thanks!

use awk ( instead of nawk )

Yes, I did get it to work using awk.
As noted, if someone can tell me why Ygor's code did not work, I would like to know. Thanks for everyone's help!

can you post the sample file which is used for the ygor script.

It's actually quite long, so it would not be a good idea to post all of it. The first two values are here:

0.002077
0.038983

All values are give to this precision. So clearly in this case both values would go to "bad.txt"
Thanks.