简体   繁体   中英

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

...

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

$ 1 == $ 1 + 0确保字符串是一个数字,然后检查它是否小于THRESHOLD_VALUE(将其更改为您希望的任何数字。如果它通过则打印出来,并排序。

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 | 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.

Another alternative is as follows:


    function compare() {
        if test $1 -lt $MAX_VALUE; then
            echo $1
        fi
    } 2> /dev/null

Have a look at help test and man bash for further help on this. The 2> /dev/null redirects errors thrown by test when you try to compare something other than two integers. Call the function like:


    compare 1
    compare -1
    compare string A

Only the middle line will give output.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM