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.
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.
Just use [a-zA-Z0-9_-] .
$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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With