bash 在bash中仅打印小于特定阈值的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6848606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 00:27:43  来源:igfitidea点击:

Print only values smaller than certain threshold in bash

bashsortingscriptingfilter

提问by Open the way

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

我有一个超过 10000 行这样的文件,主要是数字和一些字符串;

-40

-40

-50

-50

stringA

字符串A

100

100

20

20

-200

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

我想编写一个 bash(或其他)脚本,读取这个文件只输出数字(没有字符串)和那些小于零的值(或其他一些预定义的数字)。如何才能做到这一点?

In this case the output (sorted) would be

在这种情况下,输出(已排序)将是

-40

-40

-50

-50

-200

-200

...

...

回答by sampwing

cat filename | awk '{if(==+0 && <THRESHOLD_VALUE)print }' | 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.

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

回答by zkhr

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

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 -nif you don't want to sort the numbers.

其中 NUMBER 是您要用作上限的数字,而 FILENAME 是您的具有 10000 多行数字的文件。| sort -n如果您不想对数字进行排序,可以删除。

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

编辑:一个小警告。如果您的字符串以数字开头,它会将其视为该数字。否则它应该忽略它。

回答by Keith Pinson

Another alternative is as follows:

另一种选择如下:

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

Have a look at help testand man bashfor further help on this. The 2> /dev/nullredirects errors thrown by testwhen you try to compare something other than two integers. Call the function like:

看看help testman bash获得进一步的帮助。当您尝试比较两个整数以外的内容时2> /dev/null引发的重定向错误test。调用函数如下:

    compare 1
    compare -1
    compare string A

Only the middle line will give output.

只有中间线会给出输出。