Using sed to format a phone number

Formatting an unformated “phone” number using sed.

There may be a different and easier way to do this, but the main thing to learn here is the ^, $, and [[:digit:]] options.

^ refers to the first part of a line
& which is our searched for pattern
$ refers to an end part of the line
[[:digit:]] searches for, you guessed it. Digits!

The following command reads the incoming 10 digit number form echo and does the following.

the ^ tells it that the pattern needs to match at the beginning of the line
[[:digit:]] repeated tells it to search for three consecutive digits
(&) tells it to put brackets around the & which is our searched for pattern in the first part.
We then pipe that to another sed command which
searches for 4 consecutive digits
the $ tells it that it needs to be at the end of the line.

echo "1234567890" | sed -e 's/^[[:digit:]][[:digit:]][[:digit:]]/(&) /g' | sed -e 's/[[:digit:]][[:digit:]][[:digit:]][[:digit:]]$/-&/g'

Resulting output is

(123) 456-7890

The following link was helpful while searching what the ^ and $ options do.

https://www.computerhope.com/unix/used.htm

VIM/SED Search and replace lines that do not contain numbers

Objective: Find all lines in a file that only contain alpha characters and delete or replace.

Sample contents of file.

 Z2j2NH23
VTQnPwSS
hFbxgvFt
VSVR8v3F
GPrP4zo

The following sed command works for our objective.

sed s/[[:alpha:]]\{8\}/ALPHAONLY/g file.txt

The part in the [] tells sed to search for any alpha characters a-Z, the part in bold \{8\} tells it to search 8 spaces out (Change if needed) and ALPHAONLY is what alpha line will get substituted to.

sed s/[[:alpha:]]\{8\}/ALPHAONLY/g



Returns

Z2j2NH23
ALPHAONLY
ALPHAONLY
VSVR8v3F
GPrP4zo9

You can run the same basic syntax in VI

Search and replace

:%s/[[:alpha:]]\{8\}/ALPHAONLY/g 

Or to delete the lines

:%d/[[:alpha:]]\{8\}/d

You can also change [[:alpha:]] for [[:digit:]] if you want to search for numbers instead.