0

So I have a text file with lines like this:

http://sg.ovies.m/.ss/ (Status: 200) [Size: 128]
http://sg.mo.v/.dev/ (Status: 200) [Size: 12328]
http://som.b/.hal/ (Status: 200) [Size: 1238]
http://m.cb/.ho/ (Status: 200) [Size: 0]
http://sm.jo/.hK/ (Status: 200) [Size: 0]`

I would like to only grep the lines where Size is between 1 and 100.

So the output would be:

http://sg.ovies.m/.ss/ (Status: 200) [Size: 128]
http://sg.mo.v/.dev/ (Status: 200) [Size: 12328]
http://som.b/.hal/ (Status: 200) [Size: 1238]

How can it be done using grep or awk?

  • Is the trailing backtick on the last line a typo? – Kusalananda Jan 21 at 10:11
  • You say you want between 1 and 100, but in your example output all sizes are larger than 100. I've written an answer based on the 1 to 100 rule and ignored your example output. – Philip Couling Jan 21 at 10:25
  • Line 2 of your sample output appears to have a typo in the size (12328 vs likely 1238) – Jeff Schaller Jan 21 at 11:05
1

Awk makes this easy:

awk '{size=$5; sub(/]/, "", size); size=size+0; if (size <= 100 && size >= 1) {print $0 } }' file_to_read.txt

Writing this in a more friendly way:

awk '{
    # create a new variable "size".
    # items are separated by spaces, we need the 5th item
    size=$5;

    # remove the trailing "]"
    sub(/]/, "",  size);

    # make sure size is an int
    size=size+0;

    # Choose rows with seize between 1 and 100
    if (size <= 100 && size >= 1) {
        # print the whole line
        print
    }

    }'  file_to_read.txt
0

Considering that : character occurs in only 3 places in your input, we can use that as field separator, then extract the number for comparison via substring (with accounting for leading space):

awk -F':' '{size=substr( $NF,2,length($NF)-2 ); if((size>=1)&&(size<=100)) print }' input.txt

Note that you've asked for "Size: is between 1 and 100." However your sample output reads as "Size greater than 1". If that is the case, then if statement can be reduced to if(size > 1) print

-1

The following pattern should do it:

grep -E 'Size: (?:100|[1-9]|[0-9]{2})]' test

I tells grep to use extended RegEx syntax (-E) and tries to match either 100 or a value from 0 to 99 following Size:

  • I just tested this and it included the Size: 0 rows – Philip Couling Jan 21 at 10:19
  • That is true, but is such a value actually possible? – Panki Jan 21 at 10:20
  • It's in the question. When someone gives example data in a question, its best to test your answer on that example data. And yes. 0 byte HTTP responses are possible. – Philip Couling Jan 21 at 10:23
  • I have updated the pattern, it now excludes 0. – Panki Jan 21 at 10:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.