0

Hi I have a file with 5 digits zipcodes.

I am trying to use grep to print the zip codes starting 9 and can only contain digits between 4-7

The command I am using is

grep '[4-7], 9'$ zipcodesDataEntry.cvs

The problem is I am getting zipcodes that have the digits 1 2 3 8 My output should be:

95544
94554
94445
95567

However, I am getting some zipcodes such as:

91121
92231 

I am trying to exclude any numbers that are not 9 and in the range of 4-7

3

Given this infile:

cat zipcodes 
95544 94554 94445 92231 95567 91121

I can use this grep:

egrep -o '9[4-7]{4}' zipcodes 
95544
94554
94445
95567
  • 1
    The advantage of this solution, compared to the awk alternative, is that here you get only the zip codes and any "garbage" before or after it on the same line is filtered away (thanks to the -o switch). However, the question doesn't clearly state we want this filtering. Also, it's not very likely to find a Linux system with only awk, and not egrep, available. – Rein Sep 30 '16 at 14:55
0

Input file content:

95544 
94554 
94445 
95567
91121 
92231

Using awk (incase egrep not available), you can try something like this:

awk '/9[4-7]{4}/' zip.txt

Ouput:

95544 
94554 
94445 
95567
  • That will only work if the digit 9 is at the beginning of a line. Also, you are only catching two digits. – maulinglawns Sep 30 '16 at 5:54
  • Yes, thats why changed the answer using awk. – snoop Sep 30 '16 at 5:57
-1

grep '^9.[4-7].*' zipcodesDataEntry.cvs

  1. ^ The beginning of the string being compared
  2. . (Period) match any character
  3. asterisk, zero or more
  • This would give the incorrect result for a zip code like 94111 since that contains 1 and so I don't think it should be accepted. – Eric Renouf Oct 2 '16 at 11:24
  • I edited my answer. Should be grep '^9.[4-7].*' zipcodesDataEntry.cvs – Jaur Oct 2 '16 at 11:28
  • That would just make sure the third digit is between 4 and 7,not all of them – Eric Renouf Oct 2 '16 at 11:43

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.