Search code examples
bashunixkshdecimal-point

Get the value before decimal point


I am writing a Bash script. I have a variable in it which is a float value. For example:

x=2099.2

I need the value before decimal point, i.e, only 2099.


Solution

  • You can use the following shell parameter expansion:

    ${x%%.*}
    

    This removes everything from the first dot.

    See it live:

    $ v=203.4
    $ echo ${v%%.*}
    203
    
    $ v=2.3.4
    $ echo ${v%%.*}
    2
    

    From Bash Reference Manual → 3.5.3 Shell Parameter Expansion:

    ${parameter%%word}

    The word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the longest matching pattern deleted. If parameter is ‘@’ or ‘’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.