简体   繁体   中英

Printing the values falling in a range in bash

I have a file that has 1000s of lines. Out of those lines, I have to print the line that has values lying in the range of 2.0L to 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}' which gives the output as:

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?

You do not need cat here 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

awk '{print $3}' cars.csv

If this does 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

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 . && is logical AND. If you want to know more about string to number conversion read Strings And Numbers (The GNU Awk User's Guide)

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.

You can cause awk to interpret the 3th field as a number by using $3+0 . Then you can use an arithmetic function to filter the range of values like so:

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

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