Grep regex command to find ssn in datafile

I am working on something and we need a regular expression (regex) to match a Social Security number (SSN). You know SSN numbers which are nine digits long, typically grouped as 3 digits, then 2 digits, then a final 4 digits (e.g., 012-34-5678). And some time SSN are written without hyphens, so we need to make hyphens optional in the regular expression too. Can you give me such grep regex example for Linux and Unix system?

Try the following syntax for searching for an SSN when using Linux, macOS, FreeBSD/OpenBSD/NetBSD or Unix-like system from the command line

grep '[0-9]\{3\}-\{0,1\}[0-9]\{2\}-\{0,1\}[0-9]\{4\}' input_file

Searching for an SSN

For example,

cat /tmp/input_file

Sample data:


Run it:

grep '[0-9]\{3\}-\{0,1\}[0-9]\{2\}-\{0,1\}[0-9]\{4\}' input_file

For further info read my tutorial

1 Like