BASH String Slice Like Python

This is a small shell function that does the same thing a Python slicing.

function string_slice {
  STRING="$1"
  declare -i LENGTH="${#STRING}"
  declare -i START="$2"
  declare -i END="$3"

  if [ $START -lt 0 ]; then
    START=$[ $LENGTH + $START ]
  fi

  if [ $END -le 0 ]; then
    END=$[ $LENGTH + $END ]
  fi

  START=$[ $START + 1 ]
  (echo "$STRING" | cut -c $START-$END) 2> /dev/null
}

Usage

$ string_slice "12345" 0 1
1
$ string_slice "12345" 0 3
123
$ string_slice "12345" 2 3
3
$ string_slice "12345" 2 -2
3
$ string_slice "12345" -3
345

Credits

I found this code on: String Slicing in BASH Like Python

BASHStringSlice (last edited 2010-02-25 23:42:01 by CarlNobile)