Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am learning awk from this tutorial. It's quite basic.

I have a list of processes in a file which I got by doing ps aux > processes Now according to the tutorial, doing awk '$2 ~ 14022, $2 ~ 14040' should give a range of processes with PID ranging from 14022 to 14040. I tried the same with PID range 1746 - 1760. But it outputs the processes which have PID above 1760.


$ awk '$2 ~ 1746, $2 ~ 1760 {print $1, $2, $11}' processes 
root 1746 sudo
root 1750 wvdial
root 1751 /usr/sbin/pppd
dharmit 1772 /opt/google/chrome/chrome
dharmit 1788 /opt/google/chrome/chrome
dharmit 1790 /opt/google/chrome/chrome
root 1791 /sbin/udevd
dharmit 1827 /opt/google/chrome/chrome
dharmit 1830 /opt/google/chrome/chrome
dharmit 1846 /opt/google/chrome/chrome
dharmit 1850 gnome-terminal
dharmit 1856 gnome-pty-helper
dharmit 1857 bash
root 1902 [kworker/0:4]
dharmit 1940 /opt/google/chrome/chrome
root 1952 [kworker/1:0]
root 2104 /usr/sbin/anacron
root 2181 /usr/libexec/packagekitd
dharmit 2183 ps

Why does it happen so? What am I missing here?

share|improve this question
up vote 6 down vote accepted

You are specifying a range match where the end of the range does not match any of the input lines - i.e. there is no process with pid 1760.

awk is not being smart here and knowing that the field is a numeric field and comparing the PIDs against a numeric range, as you seem to be expecting. Instead it is just simply matching a string for the start and end of the range, and with no match on the end of the range, the range effectively extends to end the end of the file.

In your example, if you end the range at 1751 you will find you get what you want.

Alternatively, compare the field numerically:

awk '$2 >= 14022 && $2 <= 14040 { print }'

That will work even if your input is not sorted.

share|improve this answer
Thanks for that. It worked. – Dharmit Jul 27 '11 at 3:06

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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