Re: Best method for converting a string to a number in bash
From:
Reuti
Subject:
Re: Best method for converting a string to a number in bash
Date:
Thu, 5 Feb 2026 17:12:07 +0100
I don’t get the error you mention with `printf` but the complete string (the
"%i" might be missing in your example). Nevertheless one can also ignore all
non-digits:
echo ${@//[^0-9]/}
> Am 05.02.2026 um 16:30 schrieb Stan Marsh <gazelle@xmission.com>:
>
> The specific case that I'm concerned with is when the string is
> something like:
>
> 123abc
>
> And I want the result to be 123. I.e., convert as much as you can,
> ignore the rest. This is basically what the C library function atoi()
> (and similar) do. It is also what AWK does. But many languages,
> including bash, insist on reporting this as an error.
>
> Below is my current solution - which works well enough - but I think
> there is a more bash-y way to do it (that doesn't require dumping
> stderr), but I can't remember it now. Note: Not interested in anything
> that uses any external program, such as "awk" or "perl" or whatever;
> should be all bash builtins.
>
> poof ()
> {
> printf "$@" 2> /dev/null;
> return 0
> }
>
> bash's printf() outputs the answer, but then generates a (bogus) error
> message, so the above does the trick.
>
> ================================================================================>
> Please do not send me replies to my posts on the list.
> I always read the replies via the web archive, so CC'ing to me is unnecessary.
>
> When responding to my posts, please try to refrain from giving bureaucratic
> answers.
> If you have nothing useful to say, then just click Next and go on.
>