Question

I have a list that looks like:

#Population,    Year,   County
3900,   1969,   Beaver
3798,   1970,   Beaver
3830,   1971,   Beaver
3864,   1972,   Beaver
3993,   1973,   Beaver
3976,   1974,   Beaver
4064,   1975,   Beaver
4074,   1976,   Beaver
4064,   1977,   Beaver
4194,   1978,   Beaver
4240,   1979,   Beaver

The list is much longer but I did not include the rest. I used grep to filter the list to get only the years 1989, and then sorted it by population going from most populated to least populated, but I encountered an issue.

719048, 1989,   Salt Lake
260368, 1989,   Utah
219893, 1980,   Utah
185236, 1989,   Davis
157847, 1989,   Weber

As you can see, the third line is the year 1980, and it is being displayed because the population is 219893 and that has the number 1989 in it. How do I filter this line out?

I used this command: grep "1989" utah.txt | sort -nk1,1 -r

Is these something else I could use to get rid of that line?

Your help is appreciated.

Was it helpful?

Solution

You may need to use -w in your grep. This way it will just match whole words:

$ grep -w 1989 file
719048, 1989,   Salt Lake
260368, 1989,   Utah
185236, 1989,   Davis
157847, 1989,   Weber

Notice the difference:

$ grep 1989 file
719048, 1989,   Salt Lake
260368, 1989,   Utah
219893, 1980,   Utah   <---- without -w, this matches
185236, 1989,   Davis
157847, 1989,   Weber

If you want, awk can also do the job by indicating the field you are checking:

$ awk '$2~1989' file
719048, 1989,   Salt Lake
260368, 1989,   Utah
185236, 1989,   Davis
157847, 1989,   Weber
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top