Leo Lei | 雷雨
Nov 03, 2018
Given a text file file.txt that contains list of phone numbers (one per line), write a one liner bash script to print all valid phone numbers.
You may assume that a valid phone number must appear in one of the following two formats: (xxx) xxx-xxxx or xxx-xxx-xxxx. (x means a digit)
You may also assume each line in the text file must not contain leading or trailing white spaces.
Example:
Assume that file.txt has the following content:
987-123-4567
123 456 7890
(123) 456-7890
Your script should output the following valid phone numbers:
987-123-4567
(123) 456-7890
It's a typical problem that can be solved with Regex. Global Regular Expression Print, or grep
is one of those common tools to handle regex problems.
# Read from the file file.txt and output all valid phone numbers to stdout.
grep '^[[:digit:]]\{3\}-[[:digit:]]\{3\}-[[:digit:]]\{4\}$\|^([[:digit:]]\{3\})\ [[:digit:]]\{3\}-[[:digit:]]\{4\}$' file.txt
Sculpting text with regex, grep, sed, awk, emacs and vim by Matt Might, Professor of Internal Medicine and Computer Science at University of Alabama at Birmingham
sed is a stream editor. A stream editor is used to perform basic text transformations on an input stream (a file or input from a pipeline). While in some ways similar to an editor which permits scripted edits (such as ed), sed works by making only one pass over the input(s), and is consequently more efficient. But it is sed’s ability to filter text in a pipeline which particularly distinguishes it from other types of editors.
Online regex tester, debugger with highlighting for PHP, PCRE, Python, Golang and JavaScript.
RegExr: Learn, Build, & Test RegEx online.
None