sed: Remove All Except Digits (Numbers) From Input

Posted on in Categories , , , , , , , , last updated August 19, 2009

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

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

3 comment

Leave a Comment