sed: Remove All Except Digits (Numbers) From Input

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

🐧 Get the latest tutorials on Linux, Open Source & DevOps via RSS feed or Weekly email newsletter.

🐧 3 comments so far... add one


CategoryList of Unix and Linux commands
Disk space analyzersdf duf ncdu pydf
File Managementcat cp mkdir tree
FirewallAlpine Awall CentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Modern utilitiesbat exa
Network UtilitiesNetHogs dig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg glances gtop jobs killall kill pidof pstree pwdx time vtop
Searchingag grep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNAlpine CentOS 8 Debian 10 Firewall Ubuntu 20.04
3 comments… add one
  • Kashif Jan 25, 2012 @ 11:38

    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

    • Kashif Jan 25, 2012 @ 12:32

      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

  • Ravi Sep 19, 2015 @ 13:42

    How to remove special characters in integer value in c language?

Leave a Reply

Your email address will not be published.

Use HTML <pre>...</pre> for code samples. Still have questions? Post it on our forum