Find the answer to your Linux question:
Results 1 to 3 of 3
echo ${NUM:0:2} The above is just an example of the kind of code I'M using. I need a way to represent the end of the string. Is there a way ...
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1
    Linux Newbie
    Join Date
    Dec 2010
    Posts
    122

    bash string manipulation


    echo ${NUM:0:2}

    The above is just an example of the kind of code I'M using. I need a way to represent the end of the string. Is there a way to start from the right side of a line of text instead of the left? What I'M trying to do here is grab the last three digits on end, then the next three and so on. NUM in this case will be a user input so there is no way to hard code the end position. Thanks.

  2. #2
    Just Joined!
    Join Date
    May 2011
    Location
    Brazil
    Posts
    21
    Hey Garret85,

    Try this script:

    1 NUM=1234567
    2 SIZE=${#NUM}
    3
    4 i="0"
    5
    6
    7 while [ $i -lt $SIZE ]
    8 do
    9 echo ${NUM:$i:3}
    10 i=$[$i+3]
    11 done

    We can make some modification on above script and get your sequence starting by the last number

    Thanks,
    BR,
    Leví

  3. #3
    Trusted Penguin Irithori's Avatar
    Join Date
    May 2009
    Location
    Munich
    Posts
    3,412
    With native bash capabilites, you can only do this with regular expressions.

    Code:
    #!/usr/bin/env bash
    #
    # http://tldp.org/LDP/abs/html/refcards.html#AEN22664
    #
    
    NUM=12345678901234
    
    TAIL3=$(expr "$NUM" : '^.*\(...\)$')
    echo $TAIL3

    Fwiw, ruby is more flexible than bash here:
    Code:
    #!/usr/bin/env ruby
    
    #
    # http://www.ruby-doc.org/core-1.9.3/String.html
    #
    
    NUM = "12345678901234"
    
    puts NUM[-3..-1]
    You must always face the curtain with a bow.

  4. $spacer_open
    $spacer_close

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •