How to remove all non-numeric characters from a string in Bash?

LinuxBashShellUbuntuTerminal

Linux Problem Overview


Example:

file="123 hello"

How can I edit the string file such that it only contains the numbers and the text part is removed?

So,

echo $file

should print 123 only.

Linux Solutions


Solution 1 - Linux

This is one way with sed:

$ echo $file | sed 's/[^0-9]*//g' 
123
$ echo "123 he23llo" | sed 's/[^0-9]*//g'
12323

Or with pure bash:

$ echo "${file//[!0-9]/}" 
123
$ file="123 hello 12345 aaa"
$ echo "${file//[!0-9]/}" 
12312345

To save the result into the variable itself, do

$ file=$(echo $file | sed 's/[^0-9]*//g')
$ echo $file
123

$ file=${file//[!0-9]/}
$ echo $file
123

Solution 2 - Linux

You can say:

echo ${file%%[^0-9]*}

However, this runs into problems in certain cases:

$ file="123 file 456"
$ echo ${file%%[^0-9]*}
123

Using tr:

$ file="123 hello 456"
$ new=$(tr -dc '0-9' <<< $file)
$ echo $new
123456

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAyush MishraView Question on Stackoverflow
Solution 1 - LinuxfedorquiView Answer on Stackoverflow
Solution 2 - LinuxdevnullView Answer on Stackoverflow