OnWorks Linux and Windows Online WorkStations

Logo

Free Hosting Online for WorkStations

< Previous | Contents | Next >

Validating A Phone List With grep

In our earlier example, we looked at single phone numbers and checked them for proper formatting. A more realistic scenario would be checking a list of numbers instead, so let’s make a list. We’ll do this by reciting a magical incantation to the command line. It will be magic because we have not covered most of the commands involved, but worry not. We will get there in future chapters. Here is the incantation:



[me@linuxbox ~]$ for i in {1..10}; do echo "(${RANDOM:0:3}) ${RANDO M:0:3}-${RANDOM:0:4}" >> phonelist.txt; done

[me@linuxbox ~]$ for i in {1..10}; do echo "(${RANDOM:0:3}) ${RANDO M:0:3}-${RANDOM:0:4}" >> phonelist.txt; done


This command will produce a file named phonelist.txt containing ten phone num- bers. Each time the command is repeated, another ten numbers are added to the list. We can also change the value 10 near the beginning of the command to produce more or fewer phone numbers. If we examine the contents of the file, however, we see we have a problem:



image

[me@linuxbox ~]$ cat phonelist.txt


(232)

298-2265

(624)

381-1078

(540)

126-1980

(874)

163-2885

(286)

254-2860

(292)

108-518

(129)

44-1379

(458)

273-1642

(686)

299-8268

(198)

307-2440


Some of the numbers are malformed, which is perfect for our purposes, since we will use

grep to validate them.

One useful method of validation would be to scan the file for invalid numbers and display the resulting list:



[me@linuxbox ~]$ grep -Ev '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$'

phonelist.txt (292) 108-518

(129) 44-1379

[me@linuxbox ~]$

[me@linuxbox ~]$ grep -Ev '^\([0-9]{3}\) [0-9]{3}-[0-9]{4}$'

phonelist.txt (292) 108-518

(129) 44-1379

[me@linuxbox ~]$


Here we use the -v option to produce an inverse match so that we will only output the lines in the list that do not match the specified expression. The expression itself includes the anchor metacharacters at each end to ensure that the number has no extra characters at either end. This expression also requires that the parentheses be present in a valid num- ber, unlike our earlier phone number example.


Top OS Cloud Computing at OnWorks: