Search code examples
shellunixkshcut

Need to extract a part of a number and save it in a variable in shell scripting


Can you please help me with my query. I am running a script .ksh with 2 arguments..one of which is a number like 14103 and I want to extract 1410 out of this number and save it in a variable.

Foe e.g:

abc.ksh ST 14103

What I am doing is:

#!/bin/ksh
ENV_TYPE=$1

VER=$2

VER_N=`cut -c1-4 "$VER"`

But it is not working for me. What am I missing?


Solution

  • If you mean you want the first 4 characters, you do this entirely inside bash (which is a much better shell to use IMHO):

    VER_N=${VER:0:4}
    
    echo $VER_N
    1410
    

    If you mean you want all except the last character (again in bash):

    n=${#VER}          # Get length of VER
    ((n--))            # Decrement
    VER_N=${VER:0:$n}  # Extract all but last
    
    echo $VER_N
    1410
    

    Or all but the last character, but using sed:

    VER_N=$(sed 's/.$//' <<< $VER)