Match a specific number string

Source: Internet
Author: User

Define a file.txt file that contains the contents as follows

$Cat file. txt987-123-4567123 456 7890(123)456-7890222122-213-321 +231-456 7894321 984-4984(218)-393-3399(001)345-0000

Requires printing out a format such as (XXX) xxx-xxxx or xxx-xxx-xxxx. (x means a digit) line

Grep-e "[[:d igit:]][[:d igit:]][[:d igit:]]-[[:d igit:]][[:d igit:]][[:d igit:]]-[[:d igit:]][[:d igit:]][[:d igit:]][[ :d igit:]]| ([[:d igit:]][[:d igit:]][[:d igit:]]) [[:d Igit:]] [[:d Igit:]] [[:d igit:]]-[[:d igit:]][[:d igit:]][[:d igit:]][[:d igit:]] "file.txt

Get:

987-123-4567

321 984-4984

I can't find it.

(001) 345-0000

Grep-e "\ ([[:d igit:]][[:d igit:]][[:d igit:]]\) [[:d igit:]][[:d igit:]][[:d igit:]]-[[:d igit:]][[:d igit:]][[:d igit:] ][[:d igit:]]| [[:d Igit:]] [[:d Igit:]] [[:d igit:]]-[[:d igit:]][[:d igit:]][[:d igit:]]-[[:d igit:]][[:d igit:]][[:d igit:]][[:d igit:]] "file.txt

Get

987-123-4567

(123) 456-7890

(001) 345-0000

The parentheses are escaped, both sides of the brackets need to be escaped;

It seems so stupid, how many numbers you have to repeat [[:d igit:]]

This is a match of local conditions, such as 111 (001) 345-0000 can also be matched in; not exactly.

In other ways, use regular to match numbers

Cat File.txt | Grep-eo ' ^ (\ ([0-9]{3}\)) {1}[0-9]{3}-[0-9]{4}$|^ ([0-9]{3}-) {2}[0-9]{4}$ '

There are two matching criteria.

^ (\ ([0-9]{3}\)) {1}[0-9]{3}-[0-9]{4}$ match shape (123) 456-7890 phone number

^ ([0-9]{3}-) {2}[0-9]{4}$ matches a phone number like 987-123-4567

#using SED

Sed-n-E '/^ ([0-9]{3}-|\ ([0-9]{3}\)] [0-9]{3}-[0-9]{4}$/p ' file.txt

#using grep in Perl mode

Grep-p ' ^ (\d{3}-|\ (\d{3}\)) \d{3}-\d{4}$ ' file.txt

Match a specific number string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.