简体   繁体   English

打印落在 bash 范围内的值

[英]Printing the values falling in a range in bash

I have a file that has 1000s of lines.我有一个包含 1000 行的文件。 Out of those lines, I have to print the line that has values lying in the range of 2.0L to 4.2L.在这些行中,我必须打印值在 2.0L 到 4.2L 范围内的行。 For example, this is one of the lines in the file:例如,这是文件中的一行:

"200","94","110","Rear-wheel drive","BMW `3.0L` 6 cylinder 315hp 330 ft-lbs Turbo","True","6","6 Speed Automatic Select Shift","17","Gasoline","25","Automatic transmission","2012 BMW 740Li Sedan","BMW","2012 BMW 7 Series","2012","315","330"

I need to print the lines which fall under the range mentioned above.我需要打印属于上述范围的行。 I have successfully managed to isolate the value using cat cars.csv | awk '{print $3}'我已经成功地使用cat cars.csv | awk '{print $3}'隔离了值。 cat cars.csv | awk '{print $3}' which gives the output as: cat cars.csv | awk '{print $3}'给出 output 为:

3.5L
3.5L
3.7L
3.5L
3.7L
3.7L
3.7L
3.7L
3.5L
6.8L

But how exactly should I apply the condition in bash to restrict the values?但是我应该如何应用 bash 中的条件来限制这些值呢?

You do not need cat here cat cars.csv | awk '{print $3}'你不需要cat在这里cat cars.csv | awk '{print $3}' cat cars.csv | awk '{print $3}' as GNU AWK can handle file reading itself, just pass filename as argument that is cat cars.csv | awk '{print $3}'作为 GNU AWK可以处理文件读取本身,只需将文件名作为参数传递即可

awk '{print $3}' cars.csv

If this does output如果这样做 output

3.5L
3.5L
3.7L
3.5L
3.7L
3.7L
3.7L
3.7L
3.5L
6.8L

then you should be able to select lines with values in 2.0L to 4.2L range by doing那么你应该能够通过执行 select 行值在 2.0L 到 4.2L 范围内

awk '$3>=2.0&&$3<=4.2' cars.csv

Explantion: condition is given but not action, therefore all lines where conidition is met will be printed.解释:给出了条件但没有给出动作,因此将打印满足条件的所有行。 When comparing against numerical value GNU AWK parse longest prefix which does represent number - in this case everything before L .当与数值 GNU AWK进行比较时,解析代表数字的最长前缀 - 在本例中为L之前的所有内容。 && is logical AND. &&是逻辑与。 If you want to know more about string to number conversion read Strings And Numbers (The GNU Awk User's Guide)如果您想了解有关字符串到数字转换的更多信息,请阅读字符串和数字(GNU Awk 用户指南)

To output the lines with 2.0L to 4.2L anywhere in the line try grep -E "[23].[0-9]L|4.[012]L" cars.csv where -E tells grep to use an extended regular expression.对于 output 行中任何位置 2.0L 至 4.2L 的行,请尝试grep -E "[23].[0-9]L|4.[012]L" cars.csv其中-E告诉grep使用扩展正则表达。

You can cause awk to interpret the 3th field as a number by using $3+0 .您可以使用$3+0使 awk 将第 3 个字段解释为数字。 Then you can use an arithmetic function to filter the range of values like so:然后你可以使用算术 function 来过滤值的范围,如下所示:

cat cars.csv | awk '{if ($3+0 >= 2.0 && $3+0 <= 4.2) print $3}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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