grep or sed. How to remove certain characters

Here is my problem.

I have a list of phone numbers that I want to use only the last 4 digits as PINs for something I am working on. I have all the numbers in a file but now I want to be removed all items EXCEPT the last 4 digits.

I have seen sed commands and some grep commands but I am having some trouble.

Here is what I want to do.

file(before edit)

718-555-5465
(718) 555-1234
718-555-5678

file(after edit)

5465
1234
5678

thanks a lot guys.

sed 's/.*\(....\)/\1/' infile
1 Like
cat data | sed 's/[- ()]*//g' | awk '{print substr($1,length($1)-4,4)}'
# grep -o "....$" myfile
5465
1234
5678
echo 123-456-7890 | gawk -F"[ -]" '{print $NF}'
7890
1 Like

Another one:

sed 's/.*-//' file
# sed 's/[^[:digit:]]//g' myfile | cut -b7,8,9,10
5465
1234
5678
# cat myfile | tr -d '[:punct:]' | cut -b7,8,9,10
5465
5123
5678
# grep -o "[[:digit:]]\{4\}$" myfile
5465
1234
5678
 
# sed "s/.*[^[:digit:]\{4\}$]//g" myfile
5465
1234
5678

Thanks for the help everyone. I got this part done. Lets see how I do with my next mission.

Try this also.

echo 123-456-7890 | rev | cut -c 1-4| rev

Not the most efficient solution.

:wink:

!/bin/bash
while read -r LINE
do
  echo "${LINE:(-4)}"
done <"file"

1 Like