Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 630
Ayush Mishra Avatar asked Nov 01 '13 10:11

Ayush Mishra


People also ask

How do I remove non numeric characters from a string?

In order to remove all non-numeric characters from a string, replace() function is used. replace() Function: This function searches a string for a specific value, or a RegExp, and returns a new string where the replacement is done.

How do you remove a non alphanumeric character in Unix?

Just use [a-zA-Z0-9_-] .

What does [- Z $1 mean in Bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script.

How do I remove a character from a string in Bash?

The tr command (short for translate) is used to translate, squeeze, and delete characters from a string. You can also use tr to remove characters from a string. For demonstration purposes, we will use a sample string and then pipe it to the tr command.


1 Answers

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 
like image 139
fedorqui 'SO stop harming' Avatar answered Sep 23 '22 06:09

fedorqui 'SO stop harming'