Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract leading numbers from a string in batch script

Tags:

batch-file

cmd

I am new to batch scripting. although i have shell and python solutions for this problem but got stuck in batch script.

I have string like 123_happy, 234.healthy, 3456wealthy etc.

I want to extract the leading numbers from each string. the only pattern here is that all these strings contain numbers in the beginning.

I can't use echo %str:~0,3% as it doesn't fulfill my requirement.

like image 736
UserASR Avatar asked Sep 17 '16 08:09

UserASR


2 Answers

I think this is the simplest way:

@echo off
setlocal

set "str=123_happy"
set /A num=str
echo Result = %num%

When set /A command get a value from a variable, it convert the number until the first non-digit character with no error.

To preserve left zeros:

set "str=0128_happy"
set "num=1%str%"
set /A num=num
set "num=%num:~1%"
echo Result = %num%
like image 190
Aacini Avatar answered Sep 23 '22 23:09

Aacini


Just another option

@echo off
    setlocal enableextensions disabledelayedexpansion

    call :extractLeadingNumbers 123_happy leadingNumbers
    echo %leadingNumbers%

    call :extractLeadingNumbers 234.healthy leadingNumbers
    echo %leadingNumbers%

    call :extractLeadingNumbers "3456wealthy" leadingNumbers
    echo %leadingNumbers%

    goto :eof


rem This extracts the first numerical serie in the input string    
:extractLeadingNumbers inputString returnVar
    setlocal enableextensions disabledelayedexpansion
    rem Retrieve the string from arguments
    set "string=%~1"

    rem Use numbers as delimiters (so they are removed) to retrieve the rest of the string
    for /f "tokens=1-2 delims=0123456789 " %%a in ("%string:^"=%") do set "delimiters=%%a%%b"

    rem Use the retrieved characters as delimiters to retrieve the first numerical serie
    for /f "delims=%delimiters% " %%a in ("%string:^"=%") do set "numbers=%%a"

    rem Return the found data to caller and leave
    endlocal & set "%~2=%numbers%"
    goto :eof
like image 22
MC ND Avatar answered Sep 21 '22 23:09

MC ND