sed: Remove All Except Digits (Numbers) From Input

by Vivek Gite on August 19, 2006 · 2 comments

How do I remove all (text, special characters, white spaces, tabs etc) from my text file (input) except numbers (digits) using sed command?

You need to use simple regular expression to remove all but numbers from the input. For example, 's/^[0-9]*//g' will remove all but numbers from the input. Type the following command:
$ echo 'This is a test. 123456789 and 2nd number is 34. 3M3i4x5' | sed 's/[^0-9]*//g'
You can remove all except digits from a text file:

sed 's/[^0-9]*//g' input.txt
sed 's/[^0-9]*//g' input.txt > output.txt
sed -i 's/[^0-9]*//g' input.txt

Featured Articles:

Share this with other sys admins!
Facebook it - Tweet it - Print it -

{ 2 comments… read them below or add one }

1 Kashif January 25, 2012

Good but if I want to delete only numbers (randomly).
Input 1:
I am 89 years old.
Output 1:
I am years old.
And
Input 2:
I am 2012 years old.
Output 2:
I am 9 years old.

Thanks

Reply

2 Kashif January 25, 2012

I have figured it out. I just removed ^. But if the word contains like 82age or age10 than how it would be possible to remove only numbers.

Thanks

Reply

Leave a Comment

You can use these HTML tags and attributes for your code and commands: <strong> <em> <ol> <li> <u> <ul> <blockquote> <pre> <a href="" title="">
What is 7 + 6 ?
Please leave these two fields as-is:
Solve the simple math so we know that you are a human and not a bot.




Previous post:

Next post: