help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Best method for converting a string to a number in bash


From: Greg Wooledge
Subject: Re: Best method for converting a string to a number in bash
Date: Thu, 5 Feb 2026 11:40:52 -0500
User-agent: Mutt/1.10.1 (2018-07-13)

On Thu, Feb 05, 2026 at 08:30:30 -0700, Stan Marsh wrote:
> 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.

What if the input is "123abc456"?  What should the result be?

What if the input is "x123"?  What should the result be?

> 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
> }

I don't see how this can possibly be the full solution.  Is there a
wrapper that calls "poof" with a special format argument or something?

hobbit:~$ stan() { printf "$@" 2> /dev/null; return 0; }
hobbit:~$ stan 123abc
123abchobbit:~$ 
hobbit:~$ stan 1%s2%s3
123hobbit:~$ 

Needless to say, this is a disaster.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]