Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print only values smaller than certain threshold in bash

I have a file with more than 10000 lines like this, mostly numbers and some strings;

-40

-50

stringA

100

20

-200

...

I would like to write a bash (or other) script that reading this file only outputs numbers (no strings) and only those values smaller than zero (or some other predefined number). How can this be done?

In this case the output (sorted) would be

-40

-50

-200

...

like image 312
Open the way Avatar asked Jul 27 '11 17:07

Open the way


2 Answers

cat filename | awk '{if($1==$1+0 && $1<THRESHOLD_VALUE)print $1}' | sort -n

The $1==$1+0 ensure that the string is a number, it will then check that it is less than THRESHOLD_VALUE (change this to whatever number you wish. Print it out if it passes, and sort.

like image 66
sampwing Avatar answered Sep 25 '22 21:09

sampwing


awk '$1 < NUMBER { print }' FILENAME | sort -n

where NUMBER is the number that you want to use as an upper bound and FILENAME is your file with 10000+ lines of numbers. You can drop the | sort -n if you don't want to sort the numbers.

edit: One small caveat. If your string starts with a number, it will treat it as that number. Otherwise it should ignore it.

like image 41
zkhr Avatar answered Sep 23 '22 21:09

zkhr