Using awk how do i find numbers in a file between 200 and 400?

80 Views Asked by At

I have a file that reads something like:

500 text1 text1 text1 text1 text1 text1 (200) 
200 text2 text2 text2 text2 text2 text2
350 text3 text3 text3 text3 text3 text3
400 text4 text4 text4 text4 text4 text4 (300)
if [ -f file.txt ]      
then
    echo "Input your number:"
    read number
    if [ $number -ge 200 ] && [ $number -le 400 ]
    then 
        echo "The number that matched the file are:"
        awk $1 >= 200 && $8 <= 400 {print} numbers.txt
    else 
        echo "Number must be between 200 and 400."
    fi

Trying to extract numbers between 200 and 400 and then print the whole line and I just keep getting the while file as output instead

2

There are 2 best solutions below

1
karakfa On

change the awk line to

awk '$1>=200 && (NF>7) && substr($8,2,length($8)-2)+0<=400' numbers.txt

use substr to extract the number from the paranthesized expression and the added number of fields check will avoid false matches when there is no 8th field.

3
Ed Morton On

This MAY be what you're trying to do:

$ cat tst.sh
#!/usr/bin/env bash

file='numbers.txt'

if [[ -f "$file" ]]; then
    IFS= read -r -p 'Input your number: ' tgt

    awk -v min=200 -v max=400 -v tgt="$tgt" '
        BEGIN {
            if ( (tgt < min) || (max < tgt) ) {
                printf "Number %d must be between %d and %d.\n", tgt, min, max |"cat>&2"
                exit 1
            }
        }
        {
            delete nums
            nums[$1]
            if ( NF == 8 ) {
                nums[substr($8,2)+0]
            }

            for ( num in nums ) {
                if ( num+0 <= tgt ) {
                    print
                    next
                }
            }
        }
    ' "$file"
fi

$ ./tst.sh
Input your number: 100
Number 100 must be between 200 and 400.

$ ./tst.sh
Input your number: 200
500 text1 text1 text1 text1 text1 text1 (200)
200 text2 text2 text2 text2 text2 text2

$ ./tst.sh
Input your number: 300
500 text1 text1 text1 text1 text1 text1 (200)
200 text2 text2 text2 text2 text2 text2
400 text4 text4 text4 text4 text4 text4 (300)

$ ./tst.sh
Input your number: 400
500 text1 text1 text1 text1 text1 text1 (200)
200 text2 text2 text2 text2 text2 text2
350 text3 text3 text3 text3 text3 text3
400 text4 text4 text4 text4 text4 text4 (300)

$ ./tst.sh
Input your number: 500
Number 500 must be between 200 and 400.